c# - 我如何模拟 UserManager.GetRoles()

标签 c# asp.net unit-testing mocking asp.net-identity

如何在 ASP.NET Identity 中模拟 UserManager.GetRoles()?我知道它是一个扩展方法,所以我不能直接模拟它,也找不到需要模拟的底层方法/属性。

过去,我能够通过模拟 UserStore 来模拟扩展方法 UserManager.FindByName(),

var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
mockUserStore.Setup(x => x.FindByNameAsync(username))
                     .ReturnsAsync(new ApplicationUser() { OrganizationId = orgId });
var userManager = new ApplicationUserManager(mockUserStore.Object);

我看不到任何方法可以将角色分配给 UserStore 中的用户。有什么想法吗?

我也试过这个,但不会编译,因为 UserManager.GetRoles() 是一个扩展方法。我收到此错误:“‘Microsoft.AspNet.Identity.UserManager’不包含‘GetRoles’的定义”

public interface IApplicationUserManager
{
    IList<string> GetRoles<TUser, TKey>(TKey userId)
        where TUser : class, IUser<TKey>
        where TKey : IEquatable<TKey>;
}

public class ApplicationUserManager : UserManager<ApplicationUser>, IApplicationUserManager
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }
    public IList<string> GetRoles<TUser, TKey>(TKey userId)
        where TUser : class, IUser<TKey>
        where TKey : IEquatable<TKey>
    {
        return base.GetRoles(userId);
    }
}

最佳答案

您可以为 UserManager 制作包装器

interface IUserManagerWrapper 
{
     roles GetRoles ();
}

public class MyUserManager : IUserManagerWrapper 
{
      GetRoles () 
    {
         return UserManager.GetRoles()
    }
}

并使用 IUserManagerWrapper 而不是 UserManager.GetRoles(),因此您可以模拟它。

关于c# - 我如何模拟 UserManager.GetRoles(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829786/

相关文章:

asp.net - 列表显示为 2 列

asp.net - 在发布时更改 .config 文件中的附加程序参数值( azure 管道)

python - 单元测试二进制文件输出

c# - 在 Entity Framework 中关闭事务

c# - 有没有一种方法可以让 switch 使用 C# 8 switch 表达式返回字符串值?

c# - 如何用几行代码产生 StackOverflowException?

ASP.NET 使用 iframe for 3ds - 如何返回托管页面

c# - 尝试创建最小起订量对象

unit-testing - Grails:在单元测试期间从服务中的数据模型对象获取IndexOutOfBoundsException

c# - OwinStartup 和在 asp.net mvc 的 signalr 中启动