I am implementing Unit testing using Nunit and moq mocking framework. While testing I successfully mocked Usermanager and identity but unable to return correct value and data type.
Mock User Manager
var users = new List<MstUser>
{
new MstUser { Id=new Guid("b35ec046-423e-4ee4-a057-fcb1fe182086") ,
Email="niteshkmodi@gmail.com",
UserName = "niteshkmodi@gmail.com" }
}.AsQueryable();
var userManager = new Mock<ApplicationUserManager>();
userManager.Setup(x => x.Users).Returns(users);
// Initialize controller constructor
var controller = new HomeController(userManager.Object, adminBl);
// Calling Index Method to test
ViewResult result = await controller.Index(model, RedirectToAction) as ViewResult;
By using this code i able to mock UserManager but while testing in controller identity reference returns null
var identity = await UserManager.CreateIdentityAsync(adminUser, DefaultAuthenticationTypes.ApplicationCookie);
and i am unable to add claim and this create reference error.
identity.AddClaim(new Claim(IdentityClaimConst.FullName, adminUser.Name == null ? "" : adminUser.Name));
Mock identity
var controllerContext = new Mock<ControllerContext>();
var principal = new Moq.Mock<IPrincipal>();
principal.SetupGet(x => x.Identity.Name).Returns(userName);
controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
var controller = new HomeController(adminBl);
controller.ControllerContext = controllerContext.Object;
JsonResult result = controller.MyProfile(null, null) as JsonResult;
From this code I successfully mocking Identity but unable to access value of User.Identity.GetUserId() which give casting error
Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'System.Security.Claims.ClaimsIdentity'.