2

I have written some custom validation for some Entity Framework objects using IValidatableObject and I have added some DataAnnotations to the objects for validation.

I wanted to test that validation is meeting the required validation (ensuring that the custom validation is working and that any changes made keep those Data Annotations etc...) but I can't determine how to run the validation in the unit test without calling SaveChanges (which I don't want to do as if there is an issue and validation doesn't work it would write to the data source)

I wanted to do something like this:

[TestMethod]
public void InvalidStartDate_StartDateAfterEndDate()
{
   var header = new Header()
                    {
                        StartDate = DateTime.Now.AddDays(15),
                        EndDate = DateTime.Now.AddDays(-15)
                    };
   var actual = header.IsValid();
   var expected = false;
   Assert.AreEqual(expected, actual);
}

Or something like

[TestMethod]
public void InvalidStartDate_StartDateAfterEndDate()
{
   var header = new Header()
                    {
                        StartDate = DateTime.Now.AddDays(15),
                        EndDate = DateTime.Now.AddDays(-15)
                    };
   var actual = header.GetValidationErrors().Count;
   var expected = 0;
   Assert.AreEqual(expected, actual);
}

But can't seem to find a way of getting the validation to run without calling save changes, is there a way to do this?

1
  • db.GetValidationErrors() should work.. can you post the code for your Header class? Commented Jul 17, 2012 at 0:53

1 Answer 1

5

You can invoke the Validator to validate the object.

[TestMethod]
public void InvalidStartDate_StartDateAfterEndDate()
{
   var header = new Header()
                    {
                        StartDate = DateTime.Now.AddDays(15),
                        EndDate = DateTime.Now.AddDays(-15)
                    };

   var context = new ValidationContext(header, null, null);
   var results = new List<ValidationResult>();

   var actual = Validator.TryValidateObject(header, context, results);
   var expected = false;

   Assert.AreEqual(expected, actual);
}
Sign up to request clarification or add additional context in comments.

1 Comment

There's a fourth parameter on TryValidateObject which is a boolean responsible for iterate over all properties even those that don't have Required as an attribute - if you left it out, some validations won't happen. @Eranga, it'd be nice if you could update your answer to include it, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.