5

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 に同じ行がありますが、単体テストでは機能していないようです。

これを正しく機能させるにはどうすればよいですか?

4

1 に答える 1

12

それは正常です。この のように、検証はコントローラ アクションとは別にテストする必要があります。

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));
}

コントローラーは流暢な検証について何も知らないはずです。ここでテストする必要があるのは、ModelStateコントローラー アクションに検証エラーがある場合に正しく動作することです。このエラーが にどのように追加されたかModelStateは、個別にテストする必要がある別の問題です。

于 2011-10-06T20:04:18.577 に答える