title: .net core mvc Mocking Identity and claims and test if user has claim
body: <p>I'm trying to unit test my controller logic, it's a (.Net core 2 mvc App) I have a controller that returns details of an item if the user has specific claim, and I want to unit test that using XUnit.</p>
  
  <p>Here is the controller:</p>
  
  <pre><code>public async Task&lt;IActionResult&gt; Details(int? id)
  {
      if (id == null)
      {
          return NotFound();
      }
  
      var controlException = await _context.ControlException.FirstOrDefaultAsync(m =&gt; m.Id == id);
  
      if (controlException == null)
      {
          return NotFound();
      }
      if (User.HasClaim("control Claim", "control Claim"))
      {
              return View(controlException);
      }
      else
      {
          return RedirectToAction("AccessDenied", "Account");
      }
  
  }
  </code></pre>
  
  <p>My Unit test code is : (<code>GetContextWithData()</code> return InMemory test Database)</p>
  
  <pre><code>[Fact]
  public async Task VerifyDetailsViewType()
  {
  
      using (var context = GetContextWithData())
      using (var _controller = new ControlExceptionsController(context))
      {      
          var userStore = new Mock&lt;IUserStore&lt;ApplicationUser&gt;&gt;();
  
          var userManager = new UserManager&lt;ApplicationUser&gt;(
                           userStore.Object, null, null, null, null, null, null, null, null);
  
          var cp = new Mock&lt;ClaimsPrincipal&gt;();
          cp.Setup(m =&gt; m.HasClaim(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()))
            .Returns(true);
          cp.Setup(m =&gt; m.Identity).Returns(identityMock.Object);
  
          _controller.ControllerContext.HttpContext = new DefaultHttpContext();
          _controller.ControllerContext.HttpContext.Request.Headers["Referer"] = "http://www.test.nl";
  
          var result = await _controller.Details(888);
          Assert.IsType&lt;ViewResult&gt;(result);
      }
  }
  </code></pre>
  
  <p>My test failed because the result is "<code>RedirectToAction</code>" and not "<code>ViewResult</code>". </p>
  
  <p>I know because the user does't have the claim, so the question is how can I assign a claim to the user, in other words how can I mock the <code>Identity</code> and claims and manage this.</p>