gpt4 book ai didi

unit-testing - 单元测试 SignalR 集线器

转载 作者:行者123 更新时间:2023-11-28 19:40:10 26 4
gpt4 key购买 nike

我想在 SignalR 中测试我的集线器,最好的方法是什么?

到目前为止我想到的可能的解决方案:

  • 创建可测试的 Hub
  • 分离类的抽象逻辑
  • Selenium(想测试更小的单元)
  • 或者是否忽略了某些 SignalR 测试功能

目前使用 SignalR 0.4 和 NUnit 作为测试框架。

最佳答案

link展示了如何使用 Moq 对 SignalR hub 方法进行单元测试。您模拟存储库、客户端、上下文和调用者。这是该站点的代码,我做了一些小改动以使其适用于最新的 SignalR:

public class TestableChatHub : ChatHub  
{
public Mock<IChatRepository> MockChatRepository { get; private set; }

public TestableChatHub(Mock<IChatRepository> mockChatRepository)
: base(mockChatRepository.Object)
{
const string connectionId = "1234";
const string hubName = "Chat";
var mockConnection = new Mock<IConnection>();
var mockUser = new Mock<IPrincipal>();
var mockCookies = new Mock<IRequestCookieCollection>();

var mockRequest = new Mock<IRequest>();
mockRequest.Setup(r => r.User).Returns(mockUser.Object);
mockRequest.Setup(r => r.Cookies).Returns(mockCookies.Object);

Clients = new ClientProxy(mockConnection.Object, hubName);
Context = new HubCallerContext(mockRequest.Object, connectionId);

var trackingDictionary = new TrackingDictionary();
Caller = new StatefulSignalProxy(
mockConnection.Object, connectionId, hubName, trackingDictionary);
}
}

然后站点显示您可以使用这个可测试的中心来编写单元测试:

   [TestClass]  
public class ChatHubTests
{
private TestableChatHub _hub;

public void SetUpTests()
{
_hub = GetTestableChatHub();
}

[Test]
public void ExampleTest()
{
SetUpTests();
const string message = "test";
const string connectionId = "1234";

var result = _hub.Send(message);

_hub.MockChatRepository.Verify(r => r.SaveMessage(message, connectionId));
Assert.IsTrue(result);
}

private TestableChatHub GetTestableChatHub()
{
var mockRepository = new Mock<IChatRepository>();
mockRepository.Setup(m => m.SaveMessage(
It.IsAny<string>(), It.IsAny<string())).Returns(true);
return new TestableChatHub(mockRepository);
}
}

关于unit-testing - 单元测试 SignalR 集线器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com