[英]Test a Must rule with FluentValidation
我使用此規則來驗證屬性是否具有有效值,具體取決於另一個屬性中允許的值列表。
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);
如何改善驗證器或測試?
您可以使用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.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.