Reputation: 507
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);
}
}
Upvotes: 1
Views: 1180
Reputation: 507
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().
Upvotes: 2
Reputation: 5488
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.
Upvotes: 3