I am new to unit testing, and I need to mock the user Identity in my controller. My Test fails at User.Identity.IsAuthenticated. I get a nullReferenceException. I mean this is expected. I believe I just do not know how to use Moq with Identity.
public IActionResult Index()
{
bool isAuthenticated = User.Identity.IsAuthenticated;
if (!isAuthenticated)
{
return RedirectToPage("/Account/Login", new { area = "Identity" });
}
var claimsIdentity = (ClaimsIdentity)this.User.Identity;
var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
userId = claim.Value;
var model = new YeetViewModel();
location = _accountServices.getLocation(userId);
model.yeets = _yeetServices.GetYeetsByNew(location);
model.location = location;
return View(model);
}
This is my Test function
[Fact]
public void PassWithUser()
{
// Arrange
var controller = new YeetController(_logger);
var fakeHttpContext = new Mock<HttpContext>();
var fakeIdentity = new GenericIdentity("User");
var principal = new GenericPrincipal(fakeIdentity, null);
ViewResult views = controller.Index() as ViewResult;
// Act
// Expecting it to throw because the user inside Index is null and not set to anything
Assert.NotNull(views);
}
Please help me understand what I am doing wrong, and how to actually use Moq correctly. Sorry for my beginerness.