如何对ClientWebSocket进行集成单元测试?

oxosxuxt  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(161)

我想创建一个集成测试,它将数据发送到服务器并从ClientWebSocket获取响应。

[Fact]
public async Task WebSocket_Sending()
{
    
    var client = new ClientWebSocket();
    await client.ConnectAsync(Uri, CancellationToken.None);

    var sending = client.SendAsync(data, WebSocketMessageType.Binary, CancellationToken.None);

    var response = ????
    
    Assert.AreEqual(response, "response");
}

但是Web Socket通信不是一个发送/接收机制。所以我找不到测试结果的方法。我该怎么做呢?

8hhllhi2

8hhllhi21#

如果要测试服务器通过WebSocket连接对客户端请求的响应结果,可以使用ClientWebSocket类的ReceiveAsync方法从服务器接收响应,然后Assert该响应与预期值匹配。
您需要修改代码,如下所示:

[Fact]
public async Task WebSocket_Sending()
{
    
    var client = new ClientWebSocket();
    await client.ConnectAsync(Uri, CancellationToken.None);

    // Send the request to the server over the WebSocket connection.
    var sending = client.SendAsync(data, WebSocketMessageType.Binary, CancellationToken.None);

    // Receive the response from the server.
    var responseBuffer = new ArraySegment<byte>(new byte[1024]);
    var response = await client.ReceiveAsync(responseBuffer, CancellationToken.None);
    var responseString = Encoding.UTF8.GetString(responseBuffer, 0, response.Count);
    
    // Assert that the response is what you expect.
    Assert.AreEqual(responseString, "response");
}

您可能需要根据特定的使用情况调整缓冲区大小和编码类型。
或者,您可以使用模拟库或框架(如Moq)来模拟服务器对客户机请求的响应,并Assert客户机正在向模拟的服务器发送正确的请求数据。

相关问题