我有以下模型(所有代码都已简化)
public class BiddingTierSetViewModel
{
public List<BiddingTierViewModel> BiddingTiers { get; set; }
}
public class BiddingTierViewModel
{
public decimal StartValue { get; set; }
public decimal? EndValue { get; set; }
public decimal StepAmount { get; set; }
}
我有一套验证器
public class BiddingTierSetViewModelValidator : AbstractValidator<BiddingTierSetViewModel>
{
public BiddingTierSetViewModelValidator(IValidator<BiddingTierViewModel> biddingTierViewModelValidator)
{
RuleFor(x => x.BiddingTiers).SetCollectionValidator(biddingTierViewModelValidator);
}
}
对于集合中的每个元素
public class BiddingTierViewModelValidator : AbstractValidator<BiddingTierViewModel>
{
public BiddingTierViewModelValidator()
{
RuleFor(x => x.StartValue).GreaterThanOrEqualTo(0M);
}
}
现在,在我的测试中,我将startvalue设置为小于零
var validator = new BiddingTierViewModelValidator();
var biddingTiers =
new List<BiddingTierViewModel>()
{
new BiddingTierViewModel()
{
StartValue = -1,
EndValue = 100
}
};
biddingTierSetViewModelValidator = new BiddingTierSetViewModelValidator(
validator);
biddingTierSetViewModelValidator.ShouldHaveValidationErrorFor(b => b.BiddingTiers,
biddingTiers);
当我运行测试时,我收到错误
FluentValidation.TestHelper.ValidationTestException : Expected a validation error for the property BiddingTiers
为什么我的验证器没有抛出异常?
答案 0 :(得分:2)
好吧,我认为你在使用SetCollectionValidator时不会出错,而且你没有验证集合的“父”(在这里,你试图验证集合,但不是父集(BiddingTierSetViewModel
) )
请参阅此post