带有SignalR Core和HubContext的集成测试

时间:2019-10-23 19:27:25

标签: integration-testing asp.net-core-signalr

我遵循此blog post编写了一些带有ASP.NET Core SignalR的集成测试,当直接向Hub发送消息但没有通过HubContext时,它可以正常工作。使用HubContext时,代码执行顺序会更改。

[TestMethod]
public async Task HubContextHack()
{
    //configure TestServer code ommitted

    var hubContextMsg = string.Empty;
    connection.On<string>("OnMessageRecievedFromHubContext", msg =>
    {
        hubContextMsg = msg;
    });
    connection.On<string>("OnMessageRecievedFromHub", msg =>
    {
        hubMsg = msg;
    });
    await connection.StartAsync();

    var message = "Integration Testing in Microsoft AspNetCore SignalR";
    var hubContext = server.Host.Services
          .GetService<IHubContext<StrongEchoHub, IStrongEchoHub>>();
    await hubContext.Clients.All.OnMessageRecievedFromHubContext(message);
    //if I uncomment out this line my test passes as
    //the execution order of my code changes
    //await connection.InvokeAsync("SendFromHub", "blah " + message);

    hubContextMsg.Should().Be(message);
}

如果我在hubContextMsg = msg;中设置一个断点,则该行将被执行,但仅在 hubContextMsg.Should().Be(message);之后被执行。

screen recording of execution of integration test

Full test project here


为什么调用await connection.InvokeAsync(...);会使on处理程序在执行之后的代码之前触发?

使用HubContext时如何获得相同的行为?

0 个答案:

没有答案