我使用ASP.NET MVC 2 DataAnnotation性能上洒属性,像这样:在ASP.NET MVC如何单元测试DataAnnotationsModelBinder 2
public class LogOnViewModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Domain { get; set; }
}
我有一个单元测试,检查当前视图在验证失败时呈现。不过,我手动添加错误的ModelState
得到它的工作:
[Test]
public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails()
{
//create a invalid view model
var model = new LogOnViewModel {UserName = "jsmith"};
//Can I avoid doing this manually?
//populate Model State Errors Collection
_accountController.ModelState.AddModelError("FirstName", "First Name Required");
_accountController.ModelState.AddModelError("LastName", "Last Name Required");
var result = _accountController.LogOn(model);
result.AssertViewRendered()
.ForView(Constants.Views.LogOn)
.WithViewData<LogOnViewModel>();
}
有没有办法与ModelBinder的直接或间接地在单元测试互动?例如:
[Test]
public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails()
{
//create a invalid view model
var model = new LogOnViewModel {UserName = "jsmith"};
//validate model
//not sure about the api call...
var validationResults = new DataAnnotationsModelBinder().Validate(model);
_accountController.ModelState.Merge(validationResults);
var result = _accountController.LogOn(model);
result.AssertViewRendered()
.ForView(Constants.Views.LogOn)
.WithViewData<LogOnViewModel>();
}
嗨戴夫, 我发现这个职位后的主题,我不满意他的答案“只信任”的DataAnnotationsModelBinder所以我决定在这里发布一个问题。不管怎么说,还是要谢谢你 – lcranf 2010-01-24 22:20:16