2011-10-06 176 views
4

我在我的MVC項目中使用FluentValidation並具有以下模型和驗證:ASP.net MVC - FluentValidation單元測試

[Validator(typeof(CreateNoteModelValidator))] 
public class CreateNoteModel { 
    public string NoteText { get; set; } 
} 

public class CreateNoteModelValidator : AbstractValidator<CreateNoteModel> { 
    public CreateNoteModelValidator() { 
     RuleFor(m => m.NoteText).NotEmpty(); 
    } 
} 

我有一個控制器行動創造注:

public ActionResult Create(CreateNoteModel model) { 
    if(!ModelState.IsValid) { 
     return PartialView("Test", model); 

    // save note here 
    return Json(new { success = true })); 
} 

我寫了一個單元測試來驗證行爲:

[Test] 
public void Test_Create_With_Validation_Error() { 
    // Arrange 
    NotesController controller = new NotesController(); 
    CreateNoteModel model = new CreateNoteModel(); 

    // Act 
    ActionResult result = controller.Create(model); 

    // Assert 
    Assert.IsInstanceOfType(result, typeof(PartialViewResult)); 
} 

我的單元測試失敗,因爲它不具備任何驗證錯誤。這應該成功,因爲model.NoteText爲null,並且有一個驗證規則。

當我運行我的控制器測試時,似乎FluentValidation沒有運行。

我嘗試添加以下到我的測試:

[TestInitialize] 
public void TestInitialize() { 
    FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(); 
} 

我有我的Global.asax這條線上綁了驗證自動控制器......但它並不顯得在我的單元測試中工作。

我該如何正確工作?

回答

10

這很正常。驗證應與控制器操作like this分開進行測試。

,並測試您的控制器操作簡單模仿的ModelState錯誤:

[Test] 
public void Test_Create_With_Validation_Error() { 
    // Arrange 
    NotesController controller = new NotesController(); 
    controller.ModelState.AddModelError("NoteText", "NoteText cannot be null"); 
    CreateNoteModel model = new CreateNoteModel(); 

    // Act 
    ActionResult result = controller.Create(model); 

    // Assert 
    Assert.IsInstanceOfType(result, typeof(PartialViewResult)); 
} 

控制器不應該真正瞭解流利驗證什麼。你需要在這裏測試的是,如果在模型狀態中有一個驗證錯誤,你的控制器動作行爲正確。如何將此錯誤添加到模型狀態是另一個需要單獨測試的問題。

+1

啊,謝謝。我沒有想到像這樣在測試中添加模型錯誤。謝謝Darin。 – Dismissile