I'm trying to Mock a call of this.HttpContext.WebSockets.AcceptWebSocketAsync(), which returns an WebSocket object. My class are as follows:
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);
}
I tried mocking CreateConnectionHandler method over the interface as well but internally it is using a concrete object so it didn't help. How can I mock HttpContext to get the WebSocket method mocked object.? Any leads will be highly appreciated.
In order to mock the HttpContext
with the mocked WebSocketManager
you only need to Mock<>
the desired class, and use the Setup()
delegation to return the instantiated mocked object with Return(**.Object)
:
The mocked 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.
The mocked WebSocketManager:
Mock<WebSocketManager> mockedWebSocketManager = new Mock<WebSocketManager>();
mockedWebSocketManager
.Setup(x => x.AcceptWebSocketAsync())
.Returns(Task.FromResult(mockedWebSocket.Object));
The mocked HttpContext:
Mock<HttpContext> mockedHttpContext = new Mock<HttpContext>();
mockedHttpContext.Setup(x => x.WebSockets)
.Returns(mockedWebSocketManager.Object);
Please add using Moq;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With