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 回答