ASP.net MVC - FluentValidation单元测试

6

我正在我的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为空,有一个验证规则。

看起来当我运行控制器测试时,FluentValidation没有运行。

我尝试在我的测试中添加以下内容:

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

我在Global.asax中也有同样的代码,用于自动将验证器与控制器绑定...但是在我的单元测试中似乎无法正常工作。

我该如何正确使用它?

1个回答

13

这是正常的。验证应该与控制器操作分开测试,像这样

而要测试您的控制器操作,只需模拟一个 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是一个不同的问题,应分别进行测试。


1
啊,谢谢。我没有想到在测试中像这样添加模型错误。谢谢Darin。 - Dismissile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接