为单元测试Signalr .NetCore消息传递中心模拟Context.ConnectionId

时间:2019-07-03 14:05:44

标签: asp.net-core .net-core signalr xunit asp.net-core-signalr

我的问题是当我在.Net CORE中对我的Signalr集线器进行单元测试时,要获取一个context.connection ID值插入到我的一种方法中。我的方法在测试类中如下所示:

[Fact]
    public async Task TestWorkstationCreation()
    {
        Mock<IHubCallerClients<IWorkstation>> mockClients = new Mock<IHubCallerClients<IWorkstation>>();
        Mock<IWorkstation> mockClientProxy = new Mock<IWorkstation>();
        mockClients.Setup(clients => clients.All).Returns(mockClientProxy.Object);
        _workstationHub.Clients = mockClients.Object;
        await _workstationHub.RegisterWorkstation("WKS16", "Ready", new Dictionary<string, string> {{"OS", "Windows 10"}, {"Exam", "GRE, TOEFL"}});
        mockClientProxy.Verify(c => c.WorkstationRegistered(It.IsAny<WorkstationDataModel>(), It.IsAny<string>()), Times.AtLeastOnce);
    }

在我的中心类中,这是方法:

public async Task RegisterWorkstation(string id, string status, Dictionary<string, string> capabilities)
    {
        _logger.LogInformation(
            "Registering a Workstation with id: {id}, status: {status}, and capabilities: {capabilities}",
            id, status, string.Join(",", capabilities));
        var workstationAdded = AddWorkstation(id, status, capabilities, Context.ConnectionId);
        var message = workstationAdded == null
            ? $"A workstation with the id: {id} already exists!"
            : $"A workstation with the id: {id}, status: {status}, and capabilities: {string.Join(",", capabilities)} " +
              "was added to the current list of workstations available.";
        await Clients.All.WorkstationRegistered(workstationAdded, message);
    }

在测试时,它将在Context.ConnectionId上抛出一个未设置null指针异常的Object引用。是否有某种方式可以模拟可以使用的Context.Connection ID?

1 个答案:

答案 0 :(得分:0)

我最终为单元测试完成了这项工作,

[Fact]
    public async Task TestWorkstationCreation()
    {
        Mock<IHubCallerClients<IWorkstation>> mockClients = new Mock<IHubCallerClients<IWorkstation>>();
        Mock<IWorkstation> mockClientProxy = new Mock<IWorkstation>();
        Mock<HubCallerContext> mockClientContext = new Mock<HubCallerContext>();
        mockClients.Setup(clients => clients.All).Returns(mockClientProxy.Object);
        mockClientContext.Setup(c => c.ConnectionId).Returns(Guid.NewGuid().ToString);
        _workstationHub.Clients = mockClients.Object;
        _workstationHub.Context = mockClientContext.Object;
        await _workstationHub.RegisterWorkstation("WKS16", "Ready", new Dictionary<string, string> {{"OS", "Windows 10"}, {"Exam", "GRE, TOEFL"}});
        mockClientProxy.Verify(c => c.WorkstationRegistered(It.IsAny<WorkstationDataModel>(), It.IsAny<string>()), Times.AtLeastOnce);
    }