Mock IHttpContextAccessor in Unit Tests

前端 未结 2 1272
情深已故
情深已故 2021-01-01 09:01

I have a method to get header value using IHttpContextAccessor

public class HeaderConfiguration : IHeaderConfiguration
{
    public HeaderConfig         


        
2条回答
  •  一个人的身影
    2021-01-01 09:50

    In my scenario I had to mock IHttpContextAccessor and access the inner request url bits.
    I'm sharing it here because I spent a decent amount of time figuring this out and hopefully it'll help someone.

    readonly Mock _HttpContextAccessor = 
      new Mock(MockBehavior.Strict);
    
    void SetupHttpContextAccessorWithUrl(string currentUrl)
    {
      var httpContext = new DefaultHttpContext();
      setRequestUrl(httpContext.Request, currentUrl);
    
      _HttpContextAccessor
        .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;
      }
    }
    

提交回复
热议问题