簡體   English   中英

我如何模擬UserManager.GetRoles()

[英]How do I mock UserManager.GetRoles()

如何在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() ,因此可以對其進行模擬。

我最終為包含GetRoles的ApplicationUserManager提取了一個接口。 然后,我將GetRoles()添加到ApplicationUserManager,后者調用擴展方法類。

public interface IApplicationUserManager
{
    IList<string> GetRoles(string userId);
}

public class ApplicationUserManager : UserManager<ApplicationUser>, IApplicationUserManager
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public IList<string> GetRoles(string userId)
    {
        return UserManagerExtensions.GetRoles(manager: this, userId: userId);
    }
}

現在,我可以模擬IApplicationUserManager.GetRoles()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM