title: how do I mock Identity.UserManager<TUser>.GetUserName?
body: <p>I am trying to do Unit Testing for methods which checks if the user is logged in. I am using xunit and moq and I am able to create a mock user object with the correct claims and everything but it(_userManager.GetUserName(User);) returns null in the controller.</p>
  
  <p>I am not able to pass the mock user as a valid user in the controller method "GetUserName". </p>
  
  <pre><code>public virtual string GetUserName(System.Security.Claims.ClaimsPrincipal principal);
  /// &lt;summary&gt;
  /// Returns the User ID claim value if present otherwise returns null.
  /// &lt;/summary&gt;
  /// &lt;param name="principal"&gt;The &lt;see cref="T:System.Security.Claims.ClaimsPrincipal" /&gt; instance.&lt;/param&gt;
  /// &lt;returns&gt;The User ID claim value, or null if the claim is not present.&lt;/returns&gt;
  /// &lt;remarks&gt;The User ID claim is identified by &lt;see cref="F:System.Security.Claims.ClaimTypes.NameIdentifier" /&gt;.&lt;/remarks&gt;
  </code></pre>
  
  <p>Any help would be greatly appreciated! Thank you!</p>
  
  <p>Controller:
  When I debug the test, the line var user returns null..</p>
  
  <pre><code>[HttpPost]
  public async Task&lt;IActionResult&gt; Post([FromForm] Product productModel)
  {
      var user = _userManager.GetUserName(User);
      if (user == null)
      {
          return Json(new { success = false, value = "Please Log in to Continue." });
      }
      if (productModel.Id == Guid.Empty)
      {               
          try
          {
              productModel.CreatedBy = user;
              productModel.CreatedDate = DateTime.Now;
  
              await _unitOfWork.ProductRepo.AddProductAsync(productModel);
              await _unitOfWork.Complete();
  
              return Json(new {id=productModel.Id, success = true, value = "Successfully Added." });
           }
           catch (Exception ex)
           {
               _logging.Invoke(ex, "Failed.");
               return Json(new {success = false, value = "Failed."});
           }                
      }
  }
  </code></pre>
  
  <p>Unit Test:</p>
  
  <pre><code>[Fact]
  public async Task Post_ValidUser_EmptyId_Add_ReturnSuccess()
  {
      var user = GetUser();
  
      var userManager = _context.UserManager(user.Id, out _httpContext);
  
      var controller = new ProductsController(_mockUnitOfWork.Object, userManager, null, null);
      controller.ControllerContext.HttpContext = _httpContext;
  
      var productModel = new Product()
      {
          Id = Guid.NewGuid(),
          Title = "Test",
          CreatedDate = DateTime.Now
      };
      var result = await controller.Post(productModel);
      Assert.IsType&lt;JsonResult&gt;(result);
  
      var responseString = result as JsonResult;
      Assert.NotNull(responseString);
      var success = responseString.Value.GetType().GetProperty("success")?.GetValue(responseString.Value);
      Assert.Equal(true, success);
  }
  </code></pre>
  
  <p>InitHttpContext:</p>
  
  <pre><code>public UserManager&lt;ApplicationUser&gt; UserManager(string userId, out HttpContext httpcontext)
  {
      var claims = new List&lt;Claim&gt; { new Claim(ClaimTypes.NameIdentifier, userId) };
  
      var userManager = _serviceProvider.GetRequiredService&lt;UserManager&lt;ApplicationUser&gt;&gt;();
      var signInManager = _serviceProvider.GetRequiredService&lt;SignInManager&lt;ApplicationUser&gt;&gt;();
  
      var httpContext = _serviceProvider.GetRequiredService&lt;IHttpContextAccessor&gt;().HttpContext;
      httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
      httpcontext = httpContext;
      //controller.ControllerContext.HttpContext = httpContext;
  
      return userManager;
  }
  </code></pre>