Mocking new Microsoft Entity Framework Identity UserManager and RoleManager c# entity-framework moq unit-testing


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?

1/17/2014 7:45:31 PM

Accepted Answer

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>>()

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.

4/23/2018 1:42:42 PM

Popular Answer

I like to update the solution to this question for anyone who works on core:

    private Mock<UserManager<ApplicationUser>> GetMockUserManager()
        var userStoreMock = new Mock<IUserStore<ApplicationUser>>();
        return new Mock<UserManager<ApplicationUser>>(
            userStoreMock.Object, null, null, null, null, null, null, null, null);

Yes, 8 times null but so far there isn't any more graceful solution. If you are interested on the other parameters, take a look at the source code.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow