Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I Unit Test Data Access Layer? Is this a good practice and how to do it?

If I'm having Data Access Layer (nHibernate) for example a class called UserProvider and a Business Logic class UserBl, should I both test their methods SaveUser or GetUserById, or any other public method in DA layer which is called from BL layer. Is this a redundancy or a common practice to do?

Is it common to unit test DA layer, or that belongs to Integration test domain? Is it better to have test database, or create database data during test?

Any help is appreciated.

like image 318
nemke Avatar asked Jul 26 '10 07:07

nemke


People also ask

Should you unit test data Access Layer?

It is a good practice to write unit test for every layer, even the DAL.

How you should unit test DAO layer?

1) Always create unit test specific configuration file This may be the first step for creating unit tests for your DAO layer. Ideally, you should be using same configuration for tests as you are using for application. But there may be some changes which are only unit test specific.

How do you test a data layer?

A third way to find your data layer information is using the console tab in developer tools. Simply type “dataLayer” into the console, and voila, there's your data layer. Click the down arrow next to the data layer array, and you can see the different objects inside.


2 Answers

There's no right answer to this, it really depends. Some people (e.g Roy Osherove) say you should only test code which has conditional logic (IF statements etc), which may or may not include your DAL. Some people (often those doing TDD) will say you should test everything, including the DAL, and aim for 100% code coverage.

Personally I only test it if it has logic in, so end up with some DAL methods tested and some not. Most of the time you just end up checking that your BL calls your DAL, which has some merit but I don't find necessary. I think it makes more sense to have integration tests which cover the app end-to-end, including the database, which covers things like GetUserById.

Either way, and you probably know this already, but make sure your unit tests don't touch an actual database. (No problem doing this, but that's an integration test not a unit test, as it takes a lot longer and involves complex setup, and should be run separately).

like image 57
Grant Crofton Avatar answered Oct 19 '22 17:10

Grant Crofton


It is a good practice to write unit test for every layer, even the DAL.

I don't think running tests on the real db is a good idea, you might ruin important data. We used to set up a copy of the db for tests with just enough data in it to run tests on. In our test project we had a special web.config file with test settings, like a ConnectionString to our test db.

like image 40
gillyb Avatar answered Oct 19 '22 17:10

gillyb