.NET 8独立模式Azure Durable Function编排器单元测试疑问
独立模式Durable编排器的测试方案
你遇到的问题核心是DurableTaskClient是具体类而非接口,Moq默认无法Mock非虚方法的具体类。针对独立模式(Isolated Worker)的Durable Functions,有两种可行的测试方案:
方案一:封装DurableTaskClient为抽象接口
通过依赖反转,将对DurableTaskClient的直接依赖替换为自定义抽象接口,这样就能轻松Mock:
- 定义抽象接口,包含你需要用到的方法:
public interface IDurableClientWrapper { Task<string> ScheduleNewOrchestrationInstanceAsync(string orchestratorName); }
- 实现这个接口,内部封装真实的DurableTaskClient调用:
public class DurableClientWrapper : IDurableClientWrapper { private readonly DurableTaskClient _client; public DurableClientWrapper(DurableTaskClient client) { _client = client; } public async Task<string> ScheduleNewOrchestrationInstanceAsync(string orchestratorName) { return await _client.ScheduleNewOrchestrationInstanceAsync(orchestratorName); } }
- 修改Orchestrator类的ScheduledStart方法,依赖
IDurableClientWrapper而非直接依赖DurableTaskClient:
[Function("Orchestrator_ScheduledStart")] public async Task ScheduledStart( [TimerTrigger("* */15 * * * *")] TimerInfo timerInfo, [DurableClient] DurableTaskClient client, FunctionContext executionContext) { ILogger logger = executionContext.GetLogger("Orchestrator_ScheduledStart"); IDurableClientWrapper clientWrapper = new DurableClientWrapper(client); string instanceId = await clientWrapper.ScheduleNewOrchestrationInstanceAsync( nameof(Orchestrator)); logger.LogInformation("Started orchestration with ID = '{instanceId}'.", instanceId); }
(更优方式是通过构造函数注入IDurableClientWrapper,进一步解耦业务代码与具体实现)
- 调整测试代码,Mock
IDurableClientWrapper:
public OrchestratorTests() { mapper = new Mock<IMapper>(); repository = new Mock<IRepository>(); durableClientWrapper = new Mock<IDurableClientWrapper>(); connectorOrchestrator = new ConnectorOrchestrator(mapper.Object, repository.Object); } [Fact] public async Task ScheduledStart_ShouldTriggerOrchestrator() { TimerInfo timerInfo = new TimerInfo(); Mock<FunctionContext> functionContext = new Mock<FunctionContext>(); await connectorOrchestrator.ScheduledStart(timerInfo, durableClientWrapper.Object, functionContext.Object); durableClientWrapper.Verify(wrapper => wrapper.ScheduleNewOrchestrationInstanceAsync(nameof(Orchestrator)), Times.Once); }
方案二:使用官方测试包
微软针对独立模式提供了专门的测试工具包Microsoft.Azure.Functions.Worker.Extensions.DurableTask.Testing,其中包含TestDurableTaskClient,可以直接替代真实的DurableTaskClient进行测试:
- 安装NuGet包:
Install-Package Microsoft.Azure.Functions.Worker.Extensions.DurableTask.Testing
- 修改测试代码,使用
TestDurableTaskClient:
[Fact] public async Task ScheduledStart_ShouldTriggerOrchestrator() { TimerInfo timerInfo = new TimerInfo(); Mock<FunctionContext> functionContext = new Mock<FunctionContext>(); var testClient = new TestDurableTaskClient(); await connectorOrchestrator.ScheduledStart(timerInfo, testClient, functionContext.Object); // 验证是否成功调度了编排器 var instances = await testClient.GetInstancesAsync(); Assert.Single(instances); Assert.Equal(nameof(Orchestrator), instances.First().Name); }
这个方案不需要修改业务代码,直接用官方提供的测试客户端即可完成验证。
内容的提问来源于stack exchange,提问作者Kruti Joshi
相关产品推荐
相关产品推荐

