ChrisHDog
ChrisHDog

Reputation: 4663

Unit Testing Entity Framework Validation

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?

Upvotes: 2

Views: 1198

Answers (1)

Eranga
Eranga

Reputation: 32437

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);
}

Upvotes: 5

Related Questions