ASP.NET核心中的单元测试自定义密码验证器

时间:2017-12-26 21:50:21

标签: c# asp.net unit-testing asp.net-core

我有一个覆盖PasswordValidator的CustomPasswordValidator.cs文件

{{ ... }}

我是使用Moq和xUnit的新手。我正在尝试创建一个单元测试,以确保产生正确数量的错误(显示工作代码,代码在注释中产生错误):

 public class CustomPasswordValidator : PasswordValidator<AppUser>
    {   //override the PasswordValidator functionality with the custom definitions
        public override async Task<IdentityResult> ValidateAsync(UserManager<AppUser> manager, AppUser user, string password)
        {
            IdentityResult result = await base.ValidateAsync(manager, user, password);

            List<IdentityError> errors = result.Succeeded ? new List<IdentityError>() : result.Errors.ToList();

            //check that the username is not in the password
            if (password.ToLower().Contains(user.UserName.ToLower()))
            {
                errors.Add(new IdentityError
                {
                    Code = "PasswordContainsUserName",
                    Description = "Password cannot contain username"
                });
            }

            //check that the password doesn't contain '12345'
            if (password.Contains("12345"))
            {
                errors.Add(new IdentityError
                {
                    Code = "PasswordContainsSequence",
                    Description = "Password cannot contain numeric sequence"
                });
            }
            //return Task.FromResult(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()));
            return errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
        }
    }

IdentityResult行发生错误,表示我无法将Mock转换为UserManager,无法将Mock转换为AppUser类。

编辑:更改为包含模拟ASP.NET核心中的UserManagerClass所需的GetMockUserManager(){/ 3}}

1 个答案:

答案 0 :(得分:4)

使用Moq,您需要在模拟上调用.Object来获取模拟对象。您还应该使测试异步并等待测试中的方法。

您还在模拟测试中的主题,在这种情况下,导致被测方法在调用时返回null,因为它没有被正确设置。您基本上是在测试模拟框架。

在测试CustomPasswordValidator下创建主题的实际实例并进行测试,模拟测试对象的显式依赖关系以获得所需的行为。

public async Task Validate_Password() {

    //Arrange
    var userManagerMock = new GetMockUserManager();
    var subjetUnderTest = new CustomPasswordValidator();
    var user = new AppUser() {
        Name = "user" 
    }; 
    //set the test password to get flagged by the custom validator
    var password = "Thi$user12345";

    //Act
    IdentityResult result = await subjetUnderTest.ValidateAsync(userManagerMock.Object, user, password);


    //...code removed for brevity

}

阅读Moq Quickstart以更熟悉如何使用moq。