简体   繁体   English

使用外部事件对 C# Azure 耐用 Function 进行单元测试

[英]Unit testing an C# Azure Durable Function with external events

I've got an Azure Durable Function orchestrator that waits for two external events.我有一个 Azure 耐用 Function 协调器,它等待两个外部事件。 Once they've both been received, the orchestrator calls an activity function.一旦它们都被接收到,编排器调用一个活动 function。

Is there a way to unit test this orchestrator, to verify that the activity function is called only after both events have been received?有没有办法对这个协调器进行单元测试,以验证只有在收到两个事件后才调用活动 function?

Here's the orchestrator function code:这是编排器 function 代码:

[FunctionName("MyOrchestrator")]

public static async Task MyOrchestrator(

    [OrchestrationTrigger] IDurableOrchestrationContext context)

{
    var event1 = context.WaitForExternalEvent<string>("Event1");
    var event2 = context.WaitForExternalEvent<string>("Event2");
    await Task.WhenAll(event1, event2);

    await context.CallActivityAsync<object>("Activity1", null);
    context.SetOutput(new { Status = "Complete" });
}

If the mocked context is arranged properly then the activity can only happen after awaiting the two external event tasks to complete.如果模拟上下文安排得当,那么活动只能在等待两个外部事件任务完成后发生。

//Arrange
var context = new Mock<IDurableOrchestrationContext>(); //MOQ

context.Setup(_ => _.WaitForExternalEvent<string>(It.IsAny<string>()))
    .Returns(async () => {
        await Task.Delay(10); //Delay is optional
        return "";
    });

context.Setup(_ => _.CallActivityAsync<object>(It.IsAny<string>(), It.IsAny<object>()))
    .ReturnsAsync(null);

//Act
await MyFunction.MyOrchestrator(context.Object);

//Assert
context.Verify(_ => _.WaitForExternalEvent<string>("Event1"));
context.Verify(_ => _.WaitForExternalEvent<string>("Event2"));
context.Verify(_ => _.CallActivityAsync<object>("Activity1", null));
context.Verify(_ => _.SetOutput(It.IsAny<object>()));

In the above example, using MOQ, the events are setup generically to delay before completing the task.在上面的示例中,使用 MOQ,事件通常设置为在完成任务之前延迟。 Only then would the activity be invoked.只有这样才能调用活动。

The test then verifies specific invocations to assert the expected behaviors.然后测试验证特定的调用以断言预期的行为。

As for how useful this unit test is, not very much, since it is basically testing that framework code awaits as expected.至于这个单元测试有多大用处,不是很有用,因为它基本上是在测试框架代码是否按预期等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM