How to mock UserManager<IdentityUser>
You just do
// Arrange
var mockUser = new Mock<UserManager<IdentityUser>>();
var controller = new SweetController(mockUser.Object);
You don't need
var userManager = new UserManager(mockRepo.Object); <-- error here see image below
at all. mockUser
is already the mocked UserManager<T>
, which you place a mocked instance via mock.Object
.
When you mock an object you don't have to instantiate it with all of its dependencies (that would be integration test), that's the point of mocking (along with making methods return a desired value and do behavior tests to make sure your tested code has called a specific method with specific parameter of the mocked object).
Of course per se the above code won't work, since you didn't setup any test conditions/returns for FindByIdAsync
and IsInRoleAsync
. You have to setup these with
mockUser.Setup( userManager => userManager.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new IdentityUser { ... });
mockUser.Setup( userManager => userManager.IsInRoleAsync(It.IsAny<IdentityUser>(), "SweetTooth"))
.ReturnsAsync(true);
Then whenever the mock is called it returns your predefined user and a predefined result.