问题描述
我正在尝试为 GetUsersInRoleAsync 操作模拟 UserManager,但当我使用模拟方法时,它总是返回空值
这是代码测试
IList<ApplicationUser> users = new List<ApplicationUser>();
user = new ApplicationUser();
users.Add(user);
var mockUserManager = new Mock<UserManager<ApplicationUser>>();
var mockUserStore = new Mock<IUserStore<ApplicationUser>>().As<IUserRoleStore<ApplicationUser>>();
UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(mockUserStore.Object,null,null);
var mockUserManager2 = new Mock<UserManager<ApplicationUser>>(mockUserStore.Object);
mockUserManager2.Setup(x => x.GetUsersInRoleAsync(It.IsAny<string>())).Returns(Task.Fromresult(users));
AuthService service = new AuthService(userManager,MockIAspNetRolesRepository,_IConfigurationRoot,MockIAccountByPeopleRepository.Object,_mapper,_logger.Object,MockIModelJoins.Object,_ISendEmailsService.Object);
ResponseApi Result = await service.GetAllUsersAdmin();
Assert.Equal(Result.ResponSEObject,users);
mockUserManager2.Verify(x => x.GetUsersInRoleAsync(It.IsAny<string>()));
当我使用验证方法时,它返回
Expected invocation on the mock at least once,but was never performed: x => x.GetUsersInRoleAsync(It.IsAny<string>())
Performed invocations:
Mock<UserManager<ApplicationUser>:3> (x):
No invocations performed.
你能帮我模拟一下吗。
解决方法
您似乎没有将 UserManager
的模拟实例传递到您正在测试的 AuthService
中,因此自然不会在测试期间调用它的方法。
代码中的这一行
AuthService service = new AuthService(userManager,MockIAspNetRolesRepository,_IConfigurationRoot,MockIAccountByPeopleRepository.Object,_mapper,_logger.Object,MockIModelJoins.Object,_ISendEmailsService.Object);
应该改为
AuthService service = new AuthService(mockUserManager2.Object,_ISendEmailsService.Object);