加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.net MVC – FluentValidation单元测试

发布时间:2020-12-16 07:27:50 所属栏目:asp.Net 来源:网络整理
导读:我在我的MVC项目中使用FluentValidation并具有以下模型和验证器: [Validator(typeof(CreateNoteModelValidator))]public class CreateNoteModel { public string NoteText { get; set; }}public class CreateNoteModelValidator : AbstractValidatorCreateN
我在我的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中使用了相同的行来自动将验证器绑定到控制器……但它似乎不适用于我的单元测试.

我该如何正常工作?

解决方法

这很正常.验证应与控制器操作分开测试,like this.

要测试控制器操作,只需模拟模型状态错误:

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

控制器不应该对流畅的验证有任何了解.您需要在此测试的是,如果模型状态中存在验证错误,则控制器操作的行为正确.如何将此错误添加到模型状态是另一个需要单独测试的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读