I'm using this library to assist in unit testing a SignalR Hub with NUnit and as per best-practice, implementing custom objects, rather than individual parameters/arguments for SendAsync
Hub methods to ensure backwards compatability.
I haven't been able to get the .Verify
to pass on an example Hub method for some reason via SendCoreAsync
when trying to assert on a custom object. Although, it does pass for a simplier example utilising a single argument/parameter. See below:
namespace MyExampleHub
{
public class GameHub : Hub
{
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
}
public async Task AddUserTest(string name)
{
User user;
user = new User(Context.ConnectionId, name);
await Clients.Client(Context.ConnectionId).SendAsync("UpdateUser", user.Name);
}
}
}
namespace MyUserModel
{
public class User
{
public User(string connectionId, string name)
{
ConnectionId = connectionId;
Name = name;
}
public string ConnectionId { get; set; }
public string Name { get; set; }
}
}
namespace MyHubUnitTests
{
public class GameHubTests : HubUnitTestsBase
{
[Test]
public async Task AddUser_Should_Call_ClientsClient_with_username()
{
// Arrange
var mockHub = new GameHub();
AssignToHubRequiredProperties(mockHub);
var username = "testuser";
var connId = Guid.NewGuid().ToString();
ContextMock.Setup(x => x.ConnectionId).Returns(connId);
var mockUser = new User(connId, username);
// Act
await mockHub.AddUserTest(username);
// Assert
ClientsClientMock.Verify(c =>
c.SendCoreAsync(
"UpdateUser",
new object[] { username },
It.IsAny<CancellationToken>())
);
}
}
}
The above example test passes if I pass user.Name
to SendAsync
but not if I pass the user
object and try to assert on:
ClientsClientMock.Verify(c =>
c.SendCoreAsync(
"UpdateUser",
new object[] { mockUser },
It.IsAny<CancellationToken>())
);
See output below from Moq:
Message:โ
Moq.MockException :
Expected invocation on the mock at least once, but was never performed: c => c.SendCoreAsync("UpdateUser", [User], It.IsAny<CancellationToken>())
Performed invocations:
Mock<IClientProxy:4> (c):
IClientProxy.SendCoreAsync("UpdateUser", [User], CancellationToken)
Appreciate any advice you can give on how I can get this to work :)