gpt4 book ai didi

.net - ClientWebSocket 和单元测试

转载 作者:行者123 更新时间:2023-12-03 23:54:43 25 4
gpt4 key购买 nike

我正在使用 System.Net.WebSockets.ClientWebSocket在 .NET 4.7 应用程序中,并且在尝试使依赖于它的代码可测试时遇到问题。 ClientWebSocket是一个密封类,它定义了两个不属于抽象基类 Options 的成员(ConnectAsyncWebSocket) .因此,我无法模拟 ClientWebSocket也不使用WebSocket ,使得单元测试基本上是不可能的。

我想知道是否有人知道可模拟的.NET 的替代 Web 套接字客户端(即 ClientWebSocket 的非常薄的对象适配器就足够了)或任何其他可行的测试代码的方法取决于 ClientWebSocket .

最佳答案

将 WebSocket 包装在您需要的接口(interface)中,然后模拟该接口(interface)

带有缩写方法签名的示例:

public interface IWebSocket
{
Task<string> ReceiveDataAsync(...);
Task SendDataAsync(...);
Task CloseAsync(...);

// Add all other methods you need from the client of the websocket
}

然后实现一个适配器:

public class WebsocketAdapter : IWebSocket
{
private readonly WebSocket _websocket

public WebsocketAdapter(Websocket websocket)
{
_websocket = websocket;
}

public async Task<string> ReceiveDataAsync(...)
{
return await _websocket.ReceiveDataAsync(...);
}

public async Task SendDataAsync(...)
{
return await _websocket.SendDataAsync(...);
}

public async Task CloseAsync(...)
{
return await _websocket.CloseAsync(...);
}
}

现在你可以模拟你自己的 IWebSocket测试中的接口(interface)。

这称为 Humble Object ,一个仅包装另一个对象或静态方法调用的对象,因此您可以将其隐藏在可模拟接口(interface)后面。

关于.net - ClientWebSocket 和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50813851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com