我正在尝试对用于检查用户是否已登录的方法进行单元测试。我正在使用xunit和moq,并且能够创建具有正确声明以及除它之外的所有内容的模拟用户对象(_userManager.GetUserName(用户);)在控制器中返回null。
我无法在控制器方法“ GetUserName”中将模拟用户作为有效用户传递。
public virtual string GetUserName(System.Security.Claims.ClaimsPrincipal principal);
/// <summary>
/// Returns the User ID claim value if present otherwise returns null.
/// </summary>
/// <param name="principal">The <see cref="T:System.Security.Claims.ClaimsPrincipal" /> instance.</param>
/// <returns>The User ID claim value, or null if the claim is not present.</returns>
/// <remarks>The User ID claim is identified by <see cref="F:System.Security.Claims.ClaimTypes.NameIdentifier" />.</remarks>
任何帮助将不胜感激!谢谢!
控制器: 当我调试测试时,var用户行返回null。
[HttpPost]
public async Task<IActionResult> 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."});
}
}
}
单元测试:
[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<JsonResult>(result);
var responseString = result as JsonResult;
Assert.NotNull(responseString);
var success = responseString.Value.GetType().GetProperty("success")?.GetValue(responseString.Value);
Assert.Equal(true, success);
}
InitHttpContext:
public UserManager<ApplicationUser> UserManager(string userId, out HttpContext httpcontext)
{
var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, userId) };
var userManager = _serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var signInManager = _serviceProvider.GetRequiredService<SignInManager<ApplicationUser>>();
var httpContext = _serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
httpcontext = httpContext;
//controller.ControllerContext.HttpContext = httpContext;
return userManager;
}