实体框架验证的单元测试

编程入门 行业动态 更新时间:2024-10-10 23:22:57
本文介绍了实体框架验证的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为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.

更多推荐

实体框架验证的单元测试

本文发布于:2023-10-10 21:57:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479869.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   单元测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!