简体   繁体   English

测试实体框架3.5

[英]Testing Entity Framework 3.5

当我仅限于EF 3.5实体时,编写单元测试的最佳方法是什么?

If you're trying to unit test your queries themselves, I would strongly recommend just setting up a test database and testing them with real data. 如果您正在尝试自行对您的查询进行单元测试,我强烈建议您只设置一个测试数据库并使用实际数据对其进行测试。 Using IObjectSet<T> in order to substitute an in-memory collection for your unit tests to run against is a BAD idea. 使用IObjectSet<T>来替换内存中的集合以使单元测试运行是一个坏主意。 There are differences between how a linq query is run under linq-to-objects, and how it's parsed into a T-SQL command, namely in how nulls are handled. linq查询在linq-to-objects下运行的方式与如何将其解析为T-SQL命令(即如何处理空值)之间存在差异。 For example, 例如,

db.People.Where(p => p.AccountNum == variable);

If that's using linq-to-objects (as in some memory object set you've subbed in as a replacement for IObjectSet<T> for your unit tests) then that will run perfectly. 如果那是使用linq-to-objects(如在某些内存对象集中,你已经作为单元测试的IObjectSet<T>的替代),那么它将完美运行。 If however you're running that against a database, then if variable is null, your query will break, since a query of 但是,如果您正在针对数据库运行该操作,那么如果变量为null,则查询将中断,因为查询为

WHERE [peopleTableAlias].[AccountNum] = @param1

will be generated, with @param1 being null, which will be worthless, since you really need an IS NULL query generated. 将生成@ param1为null,这将是毫无价值的,因为您确实需要生成IS NULL查询。


If however you want to test your business logic, which calls your EF datacontext, then I would say to wrap up those queries into DataAccess objects, mark your methods as virtual, inject said DAOs where they're needed, and in your unit tests substitute either manual mocks which override those methods to return the desired value for your tests, or else do the same thing with your favorite mocking framework (ie, Rhino). 但是,如果您想测试调用EF datacontext的业务逻辑,那么我会说将这些查询包装到DataAccess对象中,将您的方法标记为虚拟,将所述DAO注入需要的位置,并在单元测试中替换手动模拟覆盖那些方法以返回测试所需的值,或者用你最喜欢的模拟框架(即Rhino)做同样的事情。

EDIT - sorry, IObjectSet<T> is limited to EF4, which you don't have, obviously. 编辑 - 抱歉, IObjectSet<T>仅限于EF4,显然你没有。 But since using that for your unit tests is something I recommended not doing, the answer should still apply. 但是,因为我建议不要使用它进行单元测试,所以答案仍然适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM