Last active
July 26, 2018 20:18
-
-
Save xleon/26f7d688737d09ce7b9b to your computer and use it in GitHub Desktop.
Attempt to test a SignalR (authorized) method (chat "SendMessage") in a one-to-one chat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public async Task SendMessage_Should_SaveData_AndReachPeer() | |
{ | |
IHubProxy proxy1 = await CreateConnectionAndGetProxy(AdminToken); | |
IHubProxy proxy2 = await CreateConnectionAndGetProxy(UserToken); | |
ChatMessageDTO pushedMessage = new ChatMessageDTO(); | |
proxy1.On<ChatMessageDTO>("AddNewMessage", m => pushedMessage = m); | |
ChatMessageEntryDTO message = new ChatMessageEntryDTO | |
{ | |
Message = "Hello from test", | |
MessageType = ChatMessageTypes.Text | |
}; | |
// when "SendMessage" is called on the server, it will broadcast a message to the other peer | |
var response = await proxy2.Invoke<ChatMessageDTO>("SendMessage", message, 1); | |
await Task.Delay(500); // give some time for signalr to broadcast the message | |
Assert.IsNotNull(response, "response is null"); | |
Assert.IsTrue(response.Id > 0, "response id is not greater than 0"); | |
Assert.IsTrue(response.ConversationId == 1, "response conversationId does not match"); | |
Assert.AreEqual(message.Message, response.Message, "response message does not match"); | |
Assert.AreEqual(message.MessageType, response.MessageType, "response MessageType does not match"); | |
Assert.IsNotNull(response.SenderId, "response SenderId is null"); | |
Assert.IsNotNull(response.SentAt, "response SentAt is null"); | |
// Assert pushed message arrived | |
Assert.IsTrue(pushedMessage.ConversationId == 1, "pushedMessage ConversationId does not match"); | |
Assert.AreEqual(pushedMessage.Message, response.Message); | |
Assert.AreEqual(pushedMessage.MessageType, response.MessageType); | |
} | |
// utility method to create a new connection with Bearer token and return the attached proxy | |
private async Task<IHubProxy> CreateConnectionAndGetProxy(AuthToken token) | |
{ | |
var connection = new HubConnection(TestAssemblyInitializer.BASE_ADDRESS); | |
AddTokenToHub(token, connection); | |
IHubProxy proxy = connection.CreateHubProxy("chatHub"); | |
await connection.Start(); | |
return proxy; | |
} | |
protected void AddTokenToHub(AuthToken authToken, HubConnection hubConnection) | |
{ | |
hubConnection.Headers.Add("Authorization", "Bearer " + authToken.Token); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
can I ask you how/when the connection is closed?