我正在尝试为Entity Framework对象的验证创建一个单元测试。我发现这个链接: stackoverflow/a/11514648/2486661 ,但验证我从来没有得到这个值。我在实体对象的属性中使用数据注释。为此,我创建一个MetaData对象,用于包含注释和注释实体对象,如下所示:
I am trying to create a unit test for the validation of an Entity Framework object. I found this link: stackoverflow/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; } }单元测试的代码:
[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); }我不明白为什么对象的验证返回值true如果我该属性的值无效。感谢任何帮助。
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.
推荐答案我使用这样的DBContext对象解决问题:
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是ObjectContext类的子类,由Entity Framework自动生成。 我还是不明白为什么使用Validator.TryValidateObject方法不起作用。
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.
更多推荐
实体框架验证的单元测试
发布评论