I am trying to mock a child collection validator, so i can write unit tests just for the validator itself.
So i have a validator that looks like this
public class ReportValidator<T> : AbstractValidator<T>
where T : Report
{
public ReportValidator(IValidator<Criteria> criteriaValidator) {
RuleFor(e => e.Name).NotEmpty();
RuleFor(e => e.MyList).SetCollectionValidator(criteriaValidator);
}
}
I have wrote a class in my test project to mock a validator, which looks like so
public class MockValidator<T> : Mock<IValidator<T>>
where T : class
{
public MockValidator()
{
this.Setup(x => x.Validate(It.IsAny<ValidationContext>()))
.Returns(new ValidationResult());
this.Setup(x => x.ValidateAsync(It.IsAny<ValidationContext>()))
.ReturnsAsync(new ValidationResult());
}
}
In my unit test i create my ReportValidator, by passing in a mock like so
public class TestReportValidator
{
private ReportValidator<Report> _validator;
[TestInitialize]
public void TestInit()
{
var mockListValidator = new MockValidator<ChildObj>();
_validator = new ReportValidator<Report>(mockListValidator.Object);
}
}
Now i have created my unit test to make sure that a report is valid like so
[TestMethod]
public void should_return_true_when_entity_is_valid()
{
var results = _validator.Validate(new Report
{
Name = "Test",
Module =
{
Id = 1,
Name = "Company"
},
MyList = new Collection<ChildObj>()
});
Assert.AreEqual(true, results.IsValid, results.IsValid ? string.Empty : results.Errors[0].ErrorMessage);
}
But i keep getting this exception
System.NullReferenceException: Object reference not set to an instance of an object.
Not sure what i am doing wrong, anyone shed some light on this?
Aucun commentaire:
Enregistrer un commentaire