【问题标题】:Test a Must rule with FluentValidation使用 FluentValidation 测试 Must 规则
【发布时间】:2018-05-11 17:14:21
【问题描述】:

我有这条规则来验证一个属性是否具有有效值,具体取决于另一个属性中的允许值列表。

model.RuleFor(c => c)
.Must(c => string.IsNullOrEmpty(c.CurrentValue) || (!string.IsNullOrEmpty(c.CurrentValue) && c.AllowedValues.Contains(c.CurrentValue)))

这很好,但我想创建一个单元测试,但总是失败。我认为是因为 RuleFor 不是针对特定属性,而是对象本身。

this.validator.ShouldNotHaveValidationErrorFor(c => c.CurrentValue, this.model);

如何改进验证器或测试?

【问题讨论】:

    标签: c# .net nunit fluentvalidation fluentvalidation-2.0


    【解决方案1】:

    您可以使用Custom 验证,以便将验证失败与特定属性联系起来:

    model.RuleFor(c => c.CurrentValue).NotEmpty();
    
    model.When(c => !string.IsNullOrEmpty(c.CurrentValue), () => Custom(CurrentValueIsAllowed));
    
    private ValidationFailure CurrentValueIsAllowed(YourModelType c)
    {
        if(c.AllowedValues.Contains(c.CurrentValue))
        {
            return null;
        } 
    
        return new ValidationFailure("CurrentValue", "Value is not allowed.");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 2015-08-27
      相关资源
      最近更新 更多