Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing for entity Framework validation

I am trying to create a unit test for the validation of an Entity Framework object. I found this link: https://stackoverflow.com/a/11514648/2486661 but the validation for me never get the value false. I am using data annotations in the properties of the entity object. For this I create a MetaData object for including the annotations and annotated the entity object like this:

[MetadataType(typeof(MyEntityObjectMetaData))]
public partial class MyEntityObject
{
}

My validation annotations are like this:

public class MyEntityObjectMetaData
{
    [StringLength(8, ErrorMessage = "Invalid Length for myProperty.")]
    public String myProperty { get; set; } 
}

And the code for the unit test:

    [TestMethod]
    public void TestMethod1()
    {
        MyEntityObject myEntityObject = new MyEntityObject();

        myEntityObject.myProperty = "1234567890";

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

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

        Assert.AreEqual(expected, actual);
    }

I do not understand why the validation of the object return the value true if I have an invalid value for the property. Thanks for any help.

like image 951
miguelbgouveia Avatar asked Mar 23 '23 10:03

miguelbgouveia


2 Answers

Here is an example of the code as part of a series of tests I run against each View Model, including a test to make sure the expected property names are there.

/// <summary>
/// Check expected properties exist.
/// </summary>
[Test]
public void Check_Expected_Properties_Exist()
{

// Get properties.
PropertyInfo propInfoFirstName = typeof(ViewModels.MyModel).GetProperty("FirstName");
PropertyInfo propInfoLastName = typeof(ViewModels.MyModel).GetProperty("LastName");

// Assert.
Assert.IsNotNull(propInfoFirstName);
Assert.IsNotNull(propInfoLastName);

}

Hope this helps.

like image 165
Karl Gjertsen Avatar answered Mar 31 '23 21:03

Karl Gjertsen


I resolve the problem using the DBContext object like this:

 MyEntityObject myEntityObject = new MyEntityObject();
 myEntityObject.myProperty = "1234567890";

var dbContext = new DbContext(MyEntityObject, true);

int errors = dbContext.GetValidationErrors().Count();

IEnumerable<DbEntityValidationResult> validationResults = 
                                         dbContext.GetValidationErrors();
DbValidationError validationError = validationResults.First().ValidationErrors.First();

Assert.AreEqual(1, errors);
Assert.AreEqual("myProperty", validationError.PropertyName);

MyEntityObject is a subclass of ObjectContext class and is auto generated by the Entity Framework. I still don't understand why using the Validator.TryValidateObject method doesn't work.

like image 28
miguelbgouveia Avatar answered Mar 31 '23 20:03

miguelbgouveia