c# - SignalR 测试 - 如何在新版本的 SignalR for ASP.NET Core 2 中模拟组

标签 c# unit-testing mocking asp.net-core-2.0 asp.net-core-signalr

我尝试为我的 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# - SignalR 测试 - 如何在新版本的 SignalR for ASP.NET Core 2 中模拟组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47471868/

相关文章:

c# - Entity Framework 在不同集合中多次引用同一个对象

c# - 如何在 WPF 中使用每张多页的 DocumentViewer 预览文档

c# - 在 WinRT 中使用 FadeInThemeAnimation 作为过渡

unit-testing - Boost 单元测试框架报告的 "mks"单元是什么?

java - 无法确定这些测试错误的原因,调试器无法在此处运行,我也无法找出解决方法

python - 为 Django 应用程序编写好的测试

asp.net-mvc-3 - 将模拟的 HttpPostedFileBase 作为 MVC 3 Controller 参数传递

c# - Moq 模拟泛型和表达式函数

c# - 在 Windows 应用商店应用程序中查看 mysql 数据库

java - Mockito 验证构造函数调用方法