简体   繁体   中英

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. 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. 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. If however you're running that against a database, then if variable is null, your query will break, since a query of

WHERE [peopleTableAlias].[AccountNum] = @param1

will be generated, with @param1 being null, which will be worthless, since you really need an IS NULL query generated.


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

EDIT - sorry, IObjectSet<T> is limited to EF4, which you don't have, obviously. But since using that for your unit tests is something I recommended not doing, the answer should still apply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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