我遵循此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);
之后被执行。
为什么调用await connection.InvokeAsync(...);
会使on
处理程序在执行之后的代码之前触发?
使用HubContext
时如何获得相同的行为?