I try to write test for my Hub method, but I don't know as because there is no documentation or code examples for current (1.0.0-alpha2-final) version of SignalR. There is my code:
[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 generates next error message while running the test:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'Moq.Language.Flow.ISetup' does not contain a definition for 'Returns'
In old versions mock clients and groups creation looks like this:
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)
But I can't use IHubCallerConnectionContext now, so I tried:
var mockClients = new Mock<IHubClients>();
but i don't know how to create mock groups in this case
Sorry for my terrible english
I don't have enough rep to comment but this link was as good as I could find for testing AspNetCore.SignalR v1.0.2:
https://buildingsteps.wordpress.com/2018/06/12/testing-signalr-hubs-in-asp-net-core-2-1/
It's still pretty ugly.
What I want to be able to do is
public Task DoCallback(IHubContext<MyHub> hubContext)
{
var clients = m_hubContext.Clients as IHubClients<IMyHubClient>;
clients.Client( "one").myCallback("Hi!");
}
Then mock out like:
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...
Hopefully in a future release...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With