jas*_*per 6 .net unit-testing websocket
我System.Net.WebSockets.ClientWebSocket
在 .NET 4.7 应用程序中使用,并且在尝试使依赖于它的代码可测试时遇到问题。ClientWebSocket
是一个密封类,它定义了两个不属于抽象基类的成员(Options
和) 。因此,我不能模拟也不能使用,使得单元测试基本上不可能。ConnectAsync
WebSocket
ClientWebSocket
WebSocket
我想知道是否有人知道 .NET 的可模拟的替代 Web 套接字客户端(即只需一个非常薄的对象适配器就ClientWebSocket
足够了)或任何其他可行的测试依赖于 .NET 的代码的方法ClientWebSocket
。
将 WebSocket 包装在您需要的接口中,然后模拟该接口
具有缩写方法签名的示例:
public interface IWebSocket
{
Task<string> ReceiveDataAsync(...);
Task SendDataAsync(...);
Task CloseAsync(...);
// Add all other methods you need from the client of the websocket
}
Run Code Online (Sandbox Code Playgroud)
然后实现一个适配器:
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(...);
}
}
Run Code Online (Sandbox Code Playgroud)
IWebSocket
现在您可以在测试中模拟您自己的界面。
这称为Humble Object,一个仅包装另一个对象或静态方法调用的对象,因此您可以将其隐藏在可模拟接口后面。