c# – SignalR测试 – 如何在新版本的SignalR for ASP.NET Core 2中模拟组
作者:互联网
我尝试为我的Hub方法编写测试,但我不知道因为没有当前(1.0.0-alpha2-final)版本的SignalR的文档或代码示例.有我的代码:
[Fact]
public void SaveVisitorInfoTest()
{
//Arrange
var chatHub = new ChatHub();
var mockClients = new Mock<IHubClients>();
chatHub.Clients = mockClients.Object;
dynamic groups = new ExpandoObject();
var groupName = "SomeConversation";
string actualName = null;
string expectedName = "someName";
groups.SendVisitorInfo = new Action<string, string>(n => {
actualName = n;
});
mockClients.Setup(_ => _.Group(groupName)).Returns(groups);
//Act
chatHub.Clients.Group(groupName).InvokeAsync("SendVisitorInfo", expectedName);
// Assert
Assert.Equal(expectedName, actualName);
}
Visual Studio在运行测试时生成下一条错误消息:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException :
‘Moq.Language.Flow.ISetup’
does not contain a definition for ‘Returns’
在旧版本中,模拟客户端和组创建如下所示:
var mockClients = new Mock<IHubCallerConnectionContext<dynamic>>();
dynamic groups = new ExpandoObject();
groups.SendVisitorInfo = new Action<string, string>(n => {
actualName = n;
});
mockClients.Setup(_ => _.Group(groupName)).Returns((ExpandoObject)groups)
但我现在不能使用IHubCallerConnectionContext,所以我试过:
var mockClients = new Mock<IHubClients>();
但在这种情况下我不知道如何创建模拟组
对不起我糟糕的英语
解决方法:
我没有足够的回复评论,但这个链接和我测试的AspNetCore.SignalR v1.0.2一样好:
https://buildingsteps.wordpress.com/2018/06/12/testing-signalr-hubs-in-asp-net-core-2-1/
它仍然很难看.
我想要做的是
public Task DoCallback(IHubContext<MyHub> hubContext)
{
var clients = m_hubContext.Clients as IHubClients<IMyHubClient>;
clients.Client( "one").myCallback("Hi!");
}
然后嘲笑:
var hubContext = new Mock<IHubContext<MyHub>>();
hubContext.Setup( h => h.Clients )
.Returns( m_hubClients.Object );
var hubClients = new Mock<IHubClients>();
var clientCallbacks = new Mock<IMyHubClient>();
hubClients.As<IHubClients<IMyHubClient>>()
.Setup( c => c.Client( "one" ) )
.Returns( clientCallbacks.Object );
clientCallbacks.Setup( c => c.myCallback( It.IsAny<string>() ) )
.Callback( ( stringp ) =>
{
...etc...
希望在未来的版本中……
标签:c,unit-testing,mocking,asp-net-core-2-0,asp-net-core-signalr 来源: https://codeday.me/bug/20190701/1348350.html