我在我的ASP.NET Core (3.1)Web API应用程序中使用SignalR,一切都很好。
然而,我需要一种方法来在单元测试中创建枢纽上下文的实例,(因为单元测试不支持DI),我在文档中没有找到任何有用的东西。
例如,我有一个manager类,我应该在我的单元测试中实例化它。
public MyManager(IHubContext<ChatHub> hubContext)
{
this.hubContext = hubContext;
...
}
我应该在我的单元测试中实例化这个类 但没有Hub上下文就不知道该怎么做了
另外,我其实不需要模拟SignalR调用,如果它们在测试中不起作用也没关系。我只是希望我的测试不会失败。
一个例子如何模拟Context与接口。
/// <summary>
/// The mock context.
/// </summary>
private static readonly Mock<IHubContext<NotificationsHub, INotificationsHub>> mockHubContext = new Mock<IHubContext<NotificationsHub, INotificationsHub>>();
然后你可以设置它像。
/// <summary>
/// Builds the notifications hub.
/// </summary>
/// <returns>NotificationsHub.</returns>
private static Mock<IHubContext<NotificationsHub, INotificationsHub>> BuildNotificationsHub()
{
// Mock
Mock<INotificationsHub> hubClientsMock = new Mock<INotificationsHub>();
// Setup
mockHubContext.Setup(mock => mock.Clients.Group(It.IsAny<string>())).Returns(hubClientsMock.Object);
mockHubContext.Setup(mock => mock.Clients.Group(It.Is<string>(group => group == "HubException"))).Throws(new HubException());
mockHubContext.Setup(mock => mock.Groups).Returns(mockGroupManager.Object);
// Return the manager
return mockHubContext;
}
微软的建议是 如果你想注入上下文的话 最好是用DI注入 而不是在构造函数中注入 就像:
private IHubContext<NotificationsHub, INotificationsHub> NotificationsHub
{
get
{
return this.serviceProvider.GetRequiredService<IHubContext<NotificationsHub, INotificationsHub>>();
}
}