![](/img/trans.png)
[英]How to mock a HttpContext.GetServerVariable() in .NET Core
[英]How to Mock this.HttpContext.WebSockets.AcceptWebSocketAsync() in c# core 2.1
我正在嘗試模擬 this.HttpContext.WebSockets.AcceptWebSocketAsync() 的調用,它返回一個 WebSocket 對象。 我的班級如下:
public abstract class HttpContext
{
protected HttpContext();
public abstract WebSocketManager WebSockets { get; }
}
public abstract class WebSocketManager
{
protected WebSocketManager();
public abstract Task<WebSocket> AcceptWebSocketAsync(string subProtocol);
}
using (var webSocket = Task.Run(async () => await
this.HttpContext.WebSockets.AcceptWebSocketAsync()))
{
socketConn.CreateConnectionHandler(obj1, obj2, webSocket.Object);
}
我也嘗試通過接口模擬 CreateConnectionHandler 方法,但在內部它使用的是具體對象,所以它沒有幫助。 如何模擬 HttpContext 以獲取 WebSocket 方法模擬對象。? 任何線索將不勝感激。
為了使用模擬的WebSocketManager
模擬HttpContext
,您只需要Mock<>
所需的類,並使用Setup()
委托通過Return(**.Object)
實例化的Mock<>
Return(**.Object)
:
模擬的 WebSocket:
Mock<System.Net.WebSockets.WebSocket> mockedWebSocket = new Mock<System.Net.WebSockets.WebSocket>();
mockedWebSocket
.Setup(x => x.SendAsync(It.IsAny<ArraySegment<byte>>(),
It.IsAny<System.Net.WebSockets.WebSocketMessageType>(),
It.IsAny<bool>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(true)); //Assuming boolean result - you will need to changed the return value according to the test case.
模擬的 WebSocketManager:
Mock<WebSocketManager> mockedWebSocketManager = new Mock<WebSocketManager>();
mockedWebSocketManager
.Setup(x => x.AcceptWebSocketAsync())
.Returns(Task.FromResult(mockedWebSocket.Object));
模擬的 HttpContext:
Mock<HttpContext> mockedHttpContext = new Mock<HttpContext>();
mockedHttpContext.Setup(x => x.WebSockets)
.Returns(mockedWebSocketManager.Object);
請using Moq;
添加using Moq;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.