Testing Modules for Framework Authentication

I am trying to create a unit test to test an Entity Framework object. I found this link: https://stackoverflow.com/a/464626/2326 , but the check for me will never get false. I use data annotations in the properties of an entity object. To do this, I create a MetaData object to include annotations and annotate the entity object as follows:

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

My validation annotations are as follows:

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

And the code for 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 object verification returns true if I have an invalid value for the property. Thanks for any help.

+4
source share
3 answers

I solve the problem using the DBContext object as follows:

  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 the ObjectContext class and is automatically generated by the Entity Framework. I still don't understand why using the Validator.TryValidateObject method does not work.

+2
source

Here is sample code as part of a series of tests that I run for each view model, including a test, to make sure the expected property names exist.

 /// <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.

+3
source

You must tell the validator to check all the properties. Dbcontext will track changes to the entity and pass certain properties to the validator.

In EF 6 you call

 var actual = Validator.TryValidateObject(myEntityObject, context, results, validateAllProperties: true); 
+1
source

Source: https://habr.com/ru/post/1501870/


All Articles