Seeing a Unit Testing in EF post on Eric Raeber's Too Much Code blog, made me remember I wrote this post (after talking to Eric about this topic) on an airplane over a week ago and never posted it.
For an architect's guidance, check out Eric's blog post as well.
One of the challenges with Unit Testing with EF is the tight association between the objectContext and database access.
The question of Unit Testing and database access is nothing new and definitely a controversial topic. With EF, the choice becomes either just skip Unit Testing for all of the "touch the database" functions or picking your poison for a workaround.
I've worked with a number of dev teams who are not stressed out about testing with Entity Framework. Here are some of the solutions they have chosen with the blessing of their architects, dev leads and DBAs. Each of these are being used by very experienced developers who have done a lot of unit testing and I trust their guidance. Granted, these solutions might not be for everyone and the last thing I want to do is get involved in another religious debate
- Copy/Paste Database: Use a small SQL Server Express database as the testing database. In the course of the particular test, copy/paste the db file to a specific location and then open a connection to it. At the end of the test, blow away the file.
- Transactions: In each of the db access tests, wrap the code within a System.Transaction.TransactionScope. At the end of the test, don't complete the transaction and the db will roll back.
- DB Script: Another client was using a small database that he would generate on the fly at the start of each test and then remove the db at the end.
There are other approaches and also tools like TypeMock. Although there's nothing official I've found on their site about EF, here is a forum thread about using TypeMock with EF: Mocking Entity Framework DataContext?
(Datacontext is a misnomer in this case since EF's context is ObjectContext.)Feel free to share your thoughts - good or bad - and your own approaches to working around this issue until EF4 provides features that are more amenable to agile development and good testing practices.
I've seen another project where the tests are grouped into those which do not touch the db and those which involve db access. That might add an extra level of comfort.




