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);

        .SetupGet(accessor => accessor.HttpContext)

    static void SetRequestUrl(HttpRequest httpRequest, string url)
            .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;


Leave a Reply

Avatar placeholder

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