我使用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