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

问题描述 投票:4回答:1

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

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

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

//test the ability to validate new passwords with Infrastructure/CustomPasswordValidator.cs 
        [Fact]
        public async void Validate_Password()
        {
            //Arrange
            <Mock><UserManager<AppUser>> userManager = new <Mock><UserManager<AppUser>>(); //caused null exception, use GetMockUserManager() instead
            <Mock><CustomPasswordValidator> customVal = new <Mock><CustomPasswordValidator>(); //caused null result object use customVal = new <CustomPasswordValidator>() instead
            <AppUser> user = new <AppUser>
            user.Name = "user" 
            //set the test password to get flagged by the custom validator
            string testPwd = "Thi$user12345";

            //Act
            //try to validate the user password
            IdentityResult result = await customVal.ValidateAsync(userManager, user, testPwd);

            //Assert
            //demonstrate that there are two errors present
            List<IdentityError> errors = result.Succeeded ? new List<IdentityError>() : result.Errors.ToList();
            Assert.Equal(errors.Count, 2);
        }

//create a mock UserManager class
        private Mock<UserManager<AppUser>> GetMockUserManager()
        {
            var userStoreMock = new Mock<IUserStore<AppUser>>();
            return new Mock<UserManager<AppUser>>(
                userStoreMock.Object, null, null, null, null, null, null, null, null);
        }

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

编辑:更改为包含模拟ASP.NET核心中的UserManagerClass所需的GetMockUserManager()(Mocking new Microsoft Entity Framework Identity UserManager and RoleManager

c# asp.net unit-testing asp.net-core
1个回答
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。

© www.soinside.com 2019 - 2024. All rights reserved.