当我们正在验证的对象具有也在验证的子类时,是否可以为 fluentvalidation 类编写单元测试。
举个例子:我的课看起来像这样
public class TestModel
{
public class SubData
{
public int SubDataVal { get; set; }
}
public int ParentVal { get; set; }
public SubData Sub { get; set; }
}
我的验证逻辑如下所示:
public class TestModelValidator : AbstractValidator<TestModel>
{
public TestModelValidator()
{
RuleFor(o => o.ParentVal).GreaterThan(0);
RuleFor(o => o.Sub.SubDataVal).GreaterThan(0);
}
}
当我编写以下单元测试时
[Test]
public void Should_have_error_when_val_is_zero()
{
validator = new TestModelValidator();
validator.ShouldHaveValidationErrorFor(model => model.ParentVal, 0);
}
我收到“System.NullReferenceException:对象引用未设置为对象的实例”。FluentValidation.TestHelper.ValidatorTester`2.ValidateError(T instanceToValidate)的异常
(如果我删除RuleFor(o => o.Sub.SubDataVal).GreaterThan(0);行,那么它可以工作!)
同样,如果我尝试对实际的子类进行单元测试:
[Test]
public void Should_have_error_when_sub_dataVal_is_zero()
{
validator = new TestModelValidator();
validator.ShouldHaveValidationErrorFor(model => model.Sub.SubDataVal, 0);
}
我收到“System.Reflection.TargetException:对象与目标类型不匹配”。来自FluentValidation.TestHelper.ValidatorTester`2.ValidateError(T instanceToValidate)