如何模拟UserManager和RoleManager进行单元测试

本文关键字:RoleManager 单元测试 UserManager 何模拟 模拟 | 更新日期: 2023-09-27 17:58:58

我模拟了抽象类来测试类的具体方法,如下所示。

var mock = new Mock<BaseTestController>();
mock.CallBase = true;
var ta = mock.Object;
ta.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };          
var owinMock = new Mock<IOwinContext>();
owinMock.Setup(o => o.Authentication.User).Returns(new ClaimsPrincipal());
owinMock.Setup(o => o.Request).Returns(new Mock<OwinRequest>().Object);
owinMock.Setup(o => o.Response).Returns(new Mock<OwinResponse>().Object);
owinMock.Setup(o => o.Environment).Returns(new Dictionary<string, object> { { "key1", 123 } });
var traceMock = new Mock<TextWriter>();
owinMock.Setup(o => o.TraceOutput).Returns(traceMock.Object);
ta.Request.SetOwinContext(owinMock.Object);
var result = await ta.ActivateDeactive("test@user.com", true);

问题:我的抽象类使用Entity Framework 6 and Asp.Net Identity UserManager and RoleManager作为以下

public TestUserManager UserService
{
    get
    {
        return _userService ?? Request.GetOwinContext().GetUserManager<TestUserManager>();
    }
    private set
    {
        _userService = value;
    }
}
public TestRoleManager RoleService
{
    get
    {
        return _roleService ?? Request.GetOwinContext().Get<TestRoleManager>();
    }
    private set
    {
        _roleService = value;
    }
}

如何在上面的模拟代码中模拟TestUserManager and TestRoleManager

我尝试了以下方法,但无法将其与controllerContext连接起来。

var userStore = new Mock<IUserStore<TestUser>>();
var userManager = new TestUserManager(userStore.Object);

Aleksey L.对以下问题的回答

这就是TestUserManager派生UserManaer并实现的方式。

public class TestUserManager : UserManager<TestUser>
{
    public TestUserManager(IUserStore<TestUser> store)
        : base(store)
    {
    }
    public static TestUserManager Create(IdentityFactoryOptions<TestUserManager> options, IOwinContext context)
    {
        TestUserManager manager = new TestUserManager(new UserStore<TestUser>(context.Get<AuthContext>()));
        setValidationRules(manager);
        IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider == null)
            dataProtectionProvider = new DpapiDataProtectionProvider();
         manager.UserTokenProvider = new DataProtectorTokenProvider<TestUser>(dataProtectionProvider.Create("ASP.NET Identity")) { TokenLifespan = TimeSpan.FromDays(expiryTime) };
        return manager;
    }
    public static TestUserManager CreateLocal(AuthContext context)
    {
        TestUserManager manager = new TestUserManager(new UserStore<TestUser>(context));
        setValidationRules(manager);
        IDataProtectionProvider dataProtectionProvider = new DpapiDataProtectionProvider();
        manager.UserTokenProvider = new DataProtectorTokenProvider<TestUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        return manager;
    }
    private static void setValidationRules(ApplicationUserManager manager)
    {
        manager.UserValidator = new UserValidator<TestUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        manager.PasswordValidator = new ApplicationPasswordValidator
        {
            RequiredLength = 30,
            MaximumCharacters = 30,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = false,
            RequireUppercase = false
        };
    }
}

控制器代码

public async Task<IHttpActionResult> ActivateDeactive(string studentId, bool active)
{
    IdentityResult result;
    _accountService = new AccountMgtService(UserService, RoleService);
    result = await _accountService.ActiveDeactiveUser(userId, active);
}

如何模拟UserManager和RoleManager进行单元测试

不确定为什么要实现TestUserManager,而不仅仅是嘲笑它。Lat说我们在控制器中有以下代码:

var owinContext = Request.GetOwinContext();
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var applicationUser = userManager.FindById("testId");

您可以通过以下方式注入模拟用户存储:

var owinMock = new Mock<IOwinContext>();
var userStoreMock = new Mock<IUserStore<ApplicationUser>>();
userStoreMock.Setup(s => s.FindByIdAsync("testId")).ReturnsAsync(new ApplicationUser
{
    Id = "testId",
    Email = "test@email.com"
});
var applicationUserManager = new ApplicationUserManager(userStoreMock.Object);
owinMock.Setup(o => o.Get<ApplicationUserManager>(It.IsAny<string>())).Returns(applicationUserManager);
ta.Request.SetOwinContext(owinMock.Object);