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?
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.
I like to update the solution to this question for anyone who works on asp.net 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With