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.