How to mock ASP.NET Identity?

In our previous blog post, Software Development: Mocks, we introduced Mocking and talked about what is mocking and why mock? In today’s post we will talk in detail about how to mock?

How to Mock?

Depending on the language of your choice, there are a wide variety of frameworks to help you Mock. In this blog post, we will use a standard ASP.NET MVC project that uses Entity Framework (EF) to connect to a database and OWIN Framework for Identity and Authentication. The web application along with the unit tests are available at our public git repo:

For Mocking we use the popular framework Moq, available as a NuGet package.

How to Mock Asp Net Identity?
ASP.NET Identity is a NuGet package that provides a rich framework to manage user profiles for your web application.

We will use a simple ToDo application to showcase our mocking example. The application allows users to register, login, add/edit their ToDo tasks. The web application uses ASP.NET Identity framework for registration and login functionality. A registered user needs to login before they can perform the add /edit actions. As would be the case, all actions would try to identify the logged in user before proceeding with the action. When you use the Identity framework, this typically looks like:

   var currentUser = UserManager.FindById(User.Identity.GetUserId());

Now to successfully test any of the actions, you will need to mock two objects from the Identity framework – User.Identity, UserManager.

Mocking the User Identity object requires that we add a mocked user with appropriate security Claims to the Controller Context of the controller that we are calling. In our example we have an action in “ToDoController” which returns all tasks of a user:

public ActionResult Index()
   var currentUser = manager.FindById(User.Identity.GetUserId());
   return View(db.ToDoes.ToList().Where(todo => todo.User.Id == currentUser.Id));

In this case, we return a mocked UserId when the code invokes User.Identity.GetUserId(). We can do this by adding a security principal to the current HttpRequest. This will be part of your mocked controller context.

   var m_HttpContext = new Mock<System.Web.HttpContextBase>();
   List claims = new List{
      new Claim("", username),
      new Claim("", userId)

   var genericIdentity = new GenericIdentity("");
   var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });

Next setup mocked HttpContext’s User property to return the generic principal from above. Now create a mocked controller context and setup mocked controller context’s “HttpContext” property to return mocked http context.

   m_HttpContext.SetupGet(x => x.User).Returns(genericPrincipal);
   m_controllerContext = new Mock();
   m_controllerContext.Setup(t => t.HttpContext).Returns(m_HttpContext.Object);

Yay, we have successfully mocked the user identity.

mock identify

Next we mock the application user manager. We can do this by creating a mocked user store and then create a mocked application user manager object. We will then set up a mocked application user manager to return the mocked user when “FindByAsync” method is called.

    var userStore = new Mock<IUserStore<ApplicationUser>>();
    var m_userManager = new Mock<UserManager<ApplicationUser>>(userStore.Object);

We can inject the above mocked user manager by calling controller constructor with user manager as parameter.

Now lets look at how we can mock the UserManager. A typical way to do this is to overload the constructor of your controller-under-test and have it take UserManager as a parameter.

   public ToDoController(MyDbContext context, UserManager userManager)
      db = context;
      manager = userManager;

In your unit test cases you would invoke the overloaded constructor and pass in the mocked UserManager.

With that you have now successfully mocked Asp.Net Identity.

This entry was posted in Best Practices, Quality, Unit Testing. Bookmark the permalink.

3 Responses to How to mock ASP.NET Identity?

  1. Ryan says:

    Thanks for this post. This post basically confirmed my understanding of mocking identity related classes.

  2. Moritz says:

    Pushed me into the right direction! thank you!

  3. Ehouarn Perret says:

    I would suggest another way of doing at least for the UserManager part:
    Inherit from User / UserManager => ApplicationUser / ApplicationUserManager
    Create an interface (or a set of interfaces) for the ApplicationUserManager assign them to the ApplicationManager and use the interface in the unit under test as dependency and tada… you just have to mock the interface/s…

Leave a Reply

Your email address will not be published. Required fields are marked *