title: Unit Test Web Api 2 Mock User
body: <p>I'm trying to mock the User.Identity in my Api Controller test.</p>
  
  <p>This is my api method:</p>
  
  <pre><code>    [Route(Urls.CustInfo.GetCustomerManagers)]
      public HttpResponseMessage GetCustomerManagers([FromUri]int groupId = -1)
      {
          var user = User.Identity.Name;
          if (IsStaff(user) &amp;&amp; groupId == -1)
          {
              return ErrorMissingQueryStringParameter;
          }
          ...
      }
  </code></pre>
  
  <p>I followed the suggestion in this post: <a href="https://stackoverflow.com/questions/15413754/set-user-property-for-an-apicontroller-in-unit-test">Set User property for an ApiController in Unit Test</a> to set the User property.</p>
  
  <p>This is my test:</p>
  
  <pre><code>    [TestMethod]
      public void User_Without_Group_Level_Access_Call_GetCustomerManagers_Should_Fail()
      {
          Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"}); 
          var response = m_controller.GetCustomerManagers();
  
          Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
      }
  </code></pre>
  
  <p>But when the test is run, the User property is always null.</p>
  
  <p>I even tried moving the line for setting the CurrentPrincipal into the api method just before calling User.Identity, but it's still null.</p>
  
  <p>What am I doing wrong? If this approach doesn't work for web api 2, what's the best way to simulate/mock the User property? </p>
  
  <p>Thanks!</p>