If you use IHttpContextAccessor in any services then you may need to mock it for unit tests. It’s quite a complicated class but in order to mock the request URL the below code can be used.

Mock<IHttpContextAccessor> SetupHttpContextAccessorWithUrl(string currentUrl)
{
    Mock<IHttpContextAccessor> mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
    var httpContext = new DefaultHttpContext();
    SetRequestUrl(httpContext.Request, currentUrl);

    mockHttpContextAccessor
        .SetupGet(accessor => accessor.HttpContext)
        .Returns(httpContext);

    static void SetRequestUrl(HttpRequest httpRequest, string url)
    {
        UriHelper
            .FromAbsolute(url, out var scheme, out var host, out var path, out var query, 
                fragment: out var _);

        httpRequest.Scheme = scheme;
        httpRequest.Host = host;
        httpRequest.Path = path;
        httpRequest.QueryString = query;
    }

    return mockHttpContextAccessor;
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *