我正在Asp.Net MVC 5中创建一个测试方法。我使用以下代码来测试我的注册方法
[TestMethod]
public async Task Registration_Test_For_Password_And_Confirm_Password_Mismatch()
{
// Arrange
var registerationModel = new RegisterViewModel() { UserName = "abc", Password = null, ConfirmPassword = "jjk", Email = "nitin.daiya@sunarctechnologies.com" };
// Validate model state start
var validationContext = new ValidationContext(registerationModel, null, null);
Validator.TryValidateObject(registerationModel, validationContext, validationResults);
foreach (var validationResult in validationResults)
{
controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
// Validate model state end
// Act
var result = await controller.Register(registerationModel) as ViewResult;
// Assert
Assert.AreEqual("", result.ViewName);
Assert.IsFalse(controller.ModelState.IsValid);
}
如果我为Required字段传递空值,则上面的代码工作正常。 如果我尝试检查任何其他验证,则表示没有显示错误消息,并且每次测试都失败。
以下是我的ViewModel
public class RegisterViewModel
{
public string UserId { get; set; }
[Required]
[System.Web.Mvc.Remote("IsUserNameAvailable", "Account", ErrorMessage = "That UserName is already taken.")]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[EmailAddress]
[System.Web.Mvc.Remote("IsEmailAvailable", "Account", ErrorMessage = "That email is already taken.")]
[Display(Name = "Email")]
public string Email { get; set; }
}
任何帮助将不胜感激
编辑:通过将Validator.TryValidateObject(registerationModel, validationContext, validationResults);
更改为Validator.TryValidateObject(registerationModel, validationContext, validationResults,true);
来解决此问题。为validateAllProperties
属性设置了True以检查所有验证。
它仍未测试远程验证。任何线索?
答案 0 :(得分:0)
Validator.TryValidateObject(registerationModel, validationContext, validationResults)
默认情况下,此行仅验证必需的属性。要验证所有属性,您需要将validateAllProperties参数设置为true:
Validator.TryValidateObject(registerationModel, validationContext, validationResults, true);
(添加此内容是因为目前尚不清楚此问题是否有答案)