Testing DAO or data access layer is always a subject of debate. What exactly we want to test? Do we just want to test the methods from DAO implementation class and making sure that each and every line of code in those methods is covered?
If we think in terms of unit-test, than our goal becomes testing every line of DAO code while really mocking all the external systems/dependencies, stubbing them in our tests. Does it bring any value?
On our side, we think that we can’t truly test a data-layer without really interacting with the database itself. And then it becomes an integration test.
Detailed Practical Example
Post Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations contains a real-world example, a trivial SpringMVC based web application which uses hibernate to save data in MySQL database. This application includes service layer and data access layer.
We wanted to test the data-access-layer of this application.
Post Spring 4 MVC+Hibernate 4+MySQL+Maven integration + Testing example using annotations contains the testing part of above mentioned post.
In order to test the data-access-layer, we decided to use integration tests for that. And the set of technologies we used to tests are common and well known.
TestNG as testing framewwork,
DBUnit in order to perform clean up/insert dummy data from predefined datasets before each test,
H2 as in-memory database for test purpose,
spring-test for application/text context management which also integrates well with TestNG. Apart from that , We’ve created a separate annotation based HibernateTestConfiguration class which prepares the LocalSessionFactoryBean using datasource and properties tailored for H2.
Please have a look on these two posts and share your opinion/feedback/experience about testing data-access-layer in general. We are open for discussion and learning together.
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.