0

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'.

niteshkumarmodi
  • 25
  • 1
  • 10
  • 1
    What exactly are you testing and why? what should be a result of your test? In my experience using too much mocks is a sign that you are testing on a wrong level or trying to test a wrong thing. – trailmax Jan 15 '18 at 09:56
  • In case of usermanager testing userlogin with right credentials that match all validations and not to create model state error. – niteshkumarmodi Jan 15 '18 at 10:15
  • In case of identity to get user id using Identity.getuserId() and pass its value in action for further execution – niteshkumarmodi Jan 15 '18 at 10:16
  • @niteshkumarmodi you have to mock the members you intend to use otherwise the mock will return null when invoked. Show the method under test and how it uses the mocked dependency in a [mcve] – Nkosi Jan 15 '18 at 12:35
  • Is it possible to mock members or UserManager extension directly. As I explored till now , I thinking to define and mock each member for test cases is not good approach for test project. Help me to know about any way to mock extension methods. – niteshkumarmodi Jan 16 '18 at 09:10

0 Answers0