Return Null reference by mocking UserManger and Identity extension functions from Moq framework

320 Views Asked by At

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="[email protected]", 
            UserName = "[email protected]" }
}.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'.

0

There are 0 best solutions below