Mocking new Microsoft Entity Framework Identity UserManager and RoleManager

Dale Alleshouse picture Dale Alleshouse · Jan 17, 2014 · Viewed 19k times · Source

Has anyone come up with a successful mocking solution for UserManager and RoleManager? I have been beating my head against a wall all day. All I want to do is mock the objects to use an in memory collection rather than hitting the Entity Framework data store. I've scoured the internet and tried several different approaches using MOQ.

I was under the impression that the new stuff was much easier to test. Am I missing something?

Answer

danludwig picture danludwig · Jan 17, 2014

Alternatively, you can mock the IUserStore<TUser> interface that UserManager accepts as an argument.

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

As @Joe Brunscheon notes in the comment below, UserManager detects support for other interfaces like IUserPasswordStore, etc. You can also moq those:

var passwordManager = userStore.As<IUserPasswordStore<ApplicationUser>>()
    .Setup(...).Returns(...);

You don't have to moq out all of these at once, you can just moq them up as needed by your code-under-test. In reality, the UserStore that EF uses to implement IUserStore implements other interfaces, and UserManager will do internal detection to see if these interfaces are implemented, and therefore, additional features supported. Fortunately, moq lets you mock up a surrogate that can implement many interfaces, using .As<T>().

In short, Microsoft.AspNet.Identity does give you everything you need to use it bare, without a wrapper, in your code. As long as you use dependency injection to instantiate your UserManager, you can safely moq it in unit tests by mocking up the interfaces it consumes and passing them via some kind of IUserStore<T> moq that is augmented to support methods on other interfaces internally detected by UserManager.