【问题标题】:ASP.net MVC - FluentValidation Unit TestsASP.net MVC - FluentValidation 单元测试
【发布时间】:2011-10-06 20:00:32
【问题描述】:

我在我的 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 中有同样的行,可以自动将验证器绑定到控制器...但它似乎在我的单元测试中不起作用。

我怎样才能让它正常工作?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 unit-testing fluentvalidation


    【解决方案1】:

    这很正常。验证应与控制器操作分开测试,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));
    }
    

    控制器不应该真正了解流利验证。您需要在这里测试的是,如果 ModelState 中存在验证错误,您的控制器操作是否正确。这个错误是如何添加到ModelState 中的,这是一个不同的问题,应该单独测试。

    【讨论】:

    • 啊,谢谢。我没有想到像这样在测试中添加模型错误。谢谢达林。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多