微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 .Net Core 测试中使用 GetUsersInRoleAsync 模拟 UserManager?

如何解决如何在 .Net Core 测试中使用 GetUsersInRoleAsync 模拟 UserManager?

我正在尝试为 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。