title: How to mock HttpContext.User
body: <p>I am working on a Asp.net MVC 5 project and I am trying to setup a mock to return a custom principal within a controller. I have search and tried different approach suggested but none of them works. </p>
  
  <p>I have a BaseController which all my controllers inherit from. The BaseController has a User property which return HttpContext.User in the getter. The HttpContext.user returns a value when called within the project but return a null when call from a unit test project.</p>
  
  <p><strong>BaseController</strong></p>
  
  <pre><code>public class BaseController : Controller
  {
      protected virtual new CustomPrincipal User
      {
          get { return HttpContext.User as CustomPrincipal; }  ***&lt;== Line with issue***
      }
  }
  </code></pre>
  
  <p><strong>Custom Principal</strong></p>
  
  <pre><code>public class CustomPrincipal : IPrincipal, ICustomPrincipal
  {
      public IIdentity Identity { get; private set; }
  
      public string UserId { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public bool   IsStoreUser { get; set; }
  
      public CustomPrincipal(string username)
      {
          this.Identity = new GenericIdentity(username);
      }
  }
  </code></pre>
  
  <p><strong>Controller</strong> </p>
  
  <pre><code>public class DocumentsController : BaseController
      {
          public ViewResult ViewDocuments()
          {
              var userType = User.IsStoreUser ? UserType.StoreUser : UserType.Corporate;  ***&lt;== User is null when calling from a unit test.***
          }
      }
  </code></pre>
  
  <p><strong>Test Case</strong></p>
  
  <pre><code>[Test]
  public void ViewDocuments_WhenCalled_ShouldReturnViewModel()
  {
      // Arrange
      var principal = new CustomPrincipal("2038786");
      principal.UserId = "2038786";
      principal.FirstName = "Test";
      principal.LastName = "User";
      principal.IsStoreUser = true;
  
      var _mockController = new Mock&lt;DocumentsController&gt;(new UnitOfWork(_context)) { CallBase = true };
          _mockController.Setup(u =&gt; u.User).Returns(principal);  ***&lt;== Error - "Invalid setup on a non-virtual (overridable in VB) member: u =&gt; u.User"***
  
      // Act
      var result = _controller.ViewDocuments();
  }
  </code></pre>
  
  <p>I'm using nUnit and Moq to create the mock object but I not sure what I'm doing wrong. I need to mock the return of User.IsStore in the DocumentControl to return the value of IsStore in the custom principal object i created in the test. </p>