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.
The idea is to develop a unit test by following these 3 simple steps: Arrange – setup the testing objects and prepare the prerequisites for your test. Act – perform the actual work of the test. Assert – verify the result.
Aim for 95% or higher coverage with unit tests for new application code. When developers unit test as they program, they improve the longevity and quality of the codebase.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With