我有一个覆盖 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 core 中模拟 UserManagerClass 所需的 GetMockUserManager() (模拟新的 Microsoft Entity Framework Identity UserManager 和 RoleManager)