Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock this.HttpContext.WebSockets.AcceptWebSocketAsync() in c# core 2.1

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.

like image 339
Sumit Chourasia Avatar asked Sep 05 '25 03:09

Sumit Chourasia


1 Answers

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;

like image 62
Shahar Shokrani Avatar answered Sep 08 '25 10:09

Shahar Shokrani