title: Unit Test Controller mocking ISession
body: <p>I want to Unit Test my Controller, but I'm having issues reading values from <code>HttpContext.Session</code>.<br>
  I want to mock this piece from my Controller: <code>HttpContext.Session.Get&lt;int&gt;(Foo)</code></p>
  
  <p>With <a href="https://stackoverflow.com/questions/41400030/mock-httpcontext-for-unit-testing-a-net-core-mvc-controller">Mock HttpContext for unit testing a .NET core MVC controller?</a> and
  <a href="https://stackoverflow.com/questions/47203333/how-to-mock-session-object-in-asp-net-core/47203926#47203926">How to mock Session Object in asp net core</a> I was able to come to the following solution:</p>
  
  <p>My Test:</p>
  
  <pre><code>public void GetFoos_AllGood_ReturnList()
  {
    //Arrange
    Mock&lt;ISession&gt; sessionMock = new Mock&lt;ISession&gt;();
    var fooSessionValue = new byte[0];
  
    Web.Controllers.FooController fooController = new Web.Controllers.FooController();
    fooController.ControllerContext.HttpContext = new DefaultHttpContext();
    fooController.ControllerContext.HttpContext.Request.Headers["Foo"] = 0;
  
    Mock&lt;IServiceCollection&gt; mock = new Mock&lt;IServiceCollection&gt;();
    mock.Object.AddSession(); // Tried this, but failed
  
    //Setup
    sessionMock.Setup(_ =&gt; _.Set("Foo", It.IsAny&lt;byte[]&gt;())).Callback&lt;string, byte[]&gt;((k, v) =&gt; fooSessionValue = v);
    sessionMock.Setup(_ =&gt; _.TryGetValue("Foo", out fooSessionValue)).Returns(true);
    mockWebDataManager.Setup(b =&gt; b.GetFoos(It.IsAny&lt;FooArgs&gt;())).Returns(new FooResult() { Foos = new List&lt;Foo&gt;() });
  
    //Act
    var result = fooController.GetFoos() as JsonResult;
  
    //Assert
    Assert.NotNull(result);
    Assert.Equal(200, result.StatusCode);
  }
  </code></pre>
  
  <p>My Controller:</p>
  
  <pre><code>internal virtual DataArgs CreateArgs()
  {
    return new FooArgs
    {
       HttpContext.Session.Get&lt;int&gt;(Foo) // I want to Mock this value    
    };
  }
  
  [HttpGet]
  public IActionResult GetFoos()
  {
    FooArgs args = CreateArgs();
    ...
  }
  </code></pre>