私は部品番号とxUnitフレームを使用してに新しいですPasswordValidatorユニットテストカスタムパスワードバリ
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());
}
}
を上書きしますCustomPasswordValidator.csファイルを持っています。私は(コメントのエラーを生成コードで動作するコードを示す)エラーの正確な数が生成されることを保証するために、ユニットテストを作成しようとしている:
//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);
}
エラーがそのIを示す、IdentityResultラインで発生しますMockをUserManagerに変換することはできず、MockをAppUserクラスに変換することはできません。
EDIT:GetMockUserManagerを含むように変更は()ASP.NETコア部品番号付(Mocking new Microsoft Entity Framework Identity UserManager and RoleManager)
これは問題であり、リンクありがとうございました – coolhand