ASP.NET Core中的单元测试密码验证器

时间:2018-07-27 12:59:40

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

我有一个CustomPasswordValidator.cs

 public class CustomPasswordValidator
{
    public int MinLength { get; set; }
    public int MaxLength { get; set; }


    public Task<IdentityResult> ValidateAsync(string item)

    {
        IdentityError errors = new IdentityError();
        MinLength = 8;
        MaxLength = 16;
        if (String.IsNullOrEmpty(item) || item.Length < MinLength || item.Length > MaxLength)

        {

            errors.Description = "password must be of minimum 8 characters ";
            return Task.FromResult(IdentityResult.Failed(errors));
        }
        //Minimum eight charachters and maximum 16 characters, at least one uppercase letter, one number and no spaces
        string pattern = @"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z@#$%^&*-_+={}|:‘,.?`~]{8,16}$";
        //@"^(?=.*[a-z])(?=.*\d)[A-Za-z\d$@$!%*?&]{8,16}";
        if (!Regex.IsMatch(item, pattern))

        {
            errors.Description = "password must at least have one uppercase letter, one number and no spaces ";
            return Task.FromResult(IdentityResult.Failed(errors));
        }

        return Task.FromResult(IdentityResult.Success);
    }
}

还有一个调用验证器类的控制器:

   public class ValidatePasswordController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult ChangePassword(ChangePasswordRequest user)
    {
        //get user data 
        string Password = user.Password;
        CustomPasswordValidator CheckPWD = new CustomPasswordValidator();
        var result = CheckPWD.ValidateAsync(Password);
        var errors = result.Result.Errors.ToArray();
        string Description = errors[0].Description;
        return Json(Description);
    }
}

我不熟悉将单元测试与TestTools.UnitTesting一起使用。我想创建一个单元测试类,以确保返回正确的结果。我该怎么办

  class PasswordValidatorTest
{

    [TestMethod]
    public void TestPWDValidation()
    {
        var password = "Thi$user12345";
        var w = new ValidatePasswordController() { }; //arrange
        //act


    }
}

0 个答案:

没有答案