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 に同じ行がありますが、単体テストでは機能していないようです。
これを正しく機能させるにはどうすればよいですか?