简体   繁体   中英

How do I mock UserManager.GetRoles()

How do I mock UserManager.GetRoles() in ASP.NET Identity? I know it's an extension method, so I can't mock it directly and I can't find the underlying methods/properties that need to be mocked.

In the past, I was able to mock the extension method UserManager.FindByName() by mocking the UserStore,

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

I don't see any way to assign Roles to the Users in the UserStore. Any ideas?

I also tried this, but won't compile because UserManager.GetRoles() is an extension method. I get this error: "'Microsoft.AspNet.Identity.UserManager' does not contain a definition for '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);
    }
}

You can make wrapper for UserManager

interface IUserManagerWrapper 
{
     roles GetRoles ();
}

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

And use IUserManagerWrapper instead of UserManager.GetRoles() , hence you can mock it.

I ended up extracting an interface for ApplicationUserManager containing GetRoles. Then I added GetRoles() to ApplicationUserManager, which calls the extension method class.

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);
    }
}

Now I can mock IApplicationUserManager.GetRoles().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM