views:

1035

answers:

3

I'm new to unit testing. But how do I unit test my DAL which is written with Entity Framework, so I can make sure my DAL code is working correctly but no database is actually touched? Could someone give as much detail as possible please.

Thanks, Ray.

Note: this post is relevant to my other post Mocking vs. Test DB? which is asked after I posted this one.

+9  A: 

If you want to test that your data access layer works correct you really need to test it against a database at some point as otherwise you aren't actually testing it works.

Garry Shutler
+1 And if a test database doesn't exist, one really should be created (seems like the OP is concerned about data updates).
Dana the Sane
What is the role of mocking, could someone explain the use of that vs. the role of a Test database?
ray247
A test database would what you would run your integration tests against (the tests of your DAL). Mocking would be used to replace your DAL for unit tests so that you just test the logic w/o actually hitting the database (e.g. You make sure your code correctly calls your DAL by providing a mock).
Todd
+1  A: 

When I unit test my DAL I use transactions and rollback at the end of the unit test, so the db is clean.

Ricardo Villamil
interesting, never thought about that, I'm sure I can google it but do you have a code snippet on how you do it?
ray247
This is not a unit-test though, but an integration test, which is fine. A lot of frameworks have their integration tests point to a separate testing database, with automatic transactions on each individual test.
Hates_
Does NUnit do this auto trans on test? If so how do I config it to do that?
ray247
Interesting approach, but I m not sure I would use it tbh, because you are not completing the operation. Why not have a tear down method that cleans up after the test?
Miau
A: 

Unit testing a DAL is a very common headache in development. For the most part, I suggest you skip it.

Most ORMs these days offer some sort of query language, be it LINQ or HQL, or some other flavor. Because a proper unit test requires that you not actually hit the database, you have to mock the ORM and doing that is the biggest pain in the ass you can think of. It's not worth it, IMO. Ultimately, you only end up testing that you wrote the proper query in your code; you get no regression value at all and can better serve your purposes by inspection of the code.

I'm not saying you shouldn't test your use of the DAL, however; just don't try unit testing. You should still have a suite of integration and user acceptance tests for your program/system; let those handle testing your data access instead.

Randolpho