title: Mock IHttpContextAccessor in Unit Tests
body: <p>I have a method to get header value using <code>IHttpContextAccessor</code></p>
  
  <pre><code>public class HeaderConfiguration : IHeaderConfiguration
  {
      public HeaderConfiguration()
      {
  
      }
  
      public string GetTenantId(IHttpContextAccessor httpContextAccessor)
      {
          return httpContextAccessor.HttpContext.Request.Headers["Tenant-ID"].ToString();
      }
  }
  </code></pre>
  
  <p>I am testing <code>GetBookByBookId</code> method</p>
  
  <p>Let's say the method looks like this:</p>
  
  <pre><code>public class Book
  {
      private readonly IHttpContextAccessor _httpContextAccessor;
      private IHeaderConfiguration _headerConfiguration;
      private string _tenantID;
  
      public Book(IHeaderConfiguration headerConfiguration, IHttpContextAccessor httpContextAccessor){
          var headerConfig = new HeaderConfiguration();
          _httpContextAccessor = httpContextAccessor;
          _tenantID = headerConfig.GetTenantId(_httpContextAccessor);
      }
  
      public Task&lt;List&lt;BookModel&gt;&gt; GetBookByBookId(string id){
          //do something with the _tenantId
          //...
      }
  }
  </code></pre>
  
  <p>Here's my unit test for <code>GetBookByBookId</code> method</p>
  
  <pre><code>[Fact]
  public void test_GetBookByBookId()
  {
      //Arrange
  
      //Mock IHttpContextAccessor
      var mockHttpContextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
  
      mockHttpContextAccessor.Setup(req =&gt; req.HttpContext.Request.Headers["Tenant-ID"].ToString()).Returns(It.IsAny&lt;string&gt;());
      //Mock HeaderConfiguration
      var mockHeaderConfiguration = new Mock&lt;IHeaderConfiguration&gt;();
      mockHeaderConfiguration.Setup(x =&gt; x.GetTenantId(mockHttpContextAccessor.Object)).Returns(It.IsAny&lt;string&gt;());
  
      var book = new Book( mockHttpContextAccessor.Object, mockHeaderConfiguration.Object);
  
      var bookId = "100";
  
      //Act
      var result = book.GetBookByBookId(bookId);
  
      //Assert
      result.Result.Should().NotBeNull().And.
          BeOfType&lt;List&lt;BookModel&gt;&gt;();
  }
  </code></pre>
  
  <p>But for this line:</p>
  
  <pre><code>mockHttpContextAccessor.Setup(req =&gt; req.HttpContext.Request.Headers["Tenant-ID"].ToString()).Returns(It.IsAny&lt;string&gt;());
  </code></pre>
  
  <p>It says </p>
  
  <blockquote>
    <p>System.NotSupportedException: 'Type to mock must be an interface or an abstract or non-sealed class. '</p>
  </blockquote>
  
  <p>I was wondering what's the proper way to mock <code>IHttpContextAccessor</code> with header value?</p>