开发者

Tools and Methods for testing Service/DAO layers in Java

I am trying to figure out the best way(s) to test Service and DAO layers. So, a few sub questions...

  1. When testing a service layer, is it best to test against a mock DAO layer or a "live" DAO layer pointed at a testing environment?
  2. How should SQL in the DAO layer be tested when the only test database is in a shared environment (Oracle/DB2)
  3. How do you solve the paradox o开发者_开发百科f any DAO writes/updates need to be tested with DAO reads which is something that also has to be tested?

I am looking for any good documentation, articles, or references in this area along with any tools to help automate the process. I already know about JUint for unit testing and Hudson for CI.


Get Growing Object-Oriented Software, Guided by Tests. It has some great tips about how to test database access.

Personally, I usually break the DAO tests in 2, a unit test with a mocked database to test functionality on the DAO, and an integration test, to test the queries against the DB. If your DAO only has database access code, you won't need a unit test.

One of the suggestions from the book that I took, is that the (integration) test has to commit the changes to the DB. I've learn to do this, after using hibernate and figuring out that the test was marked for rollback and the DB never got the insert statement. If you use triggers or any kind of validation (even FKs) I think this is a must.

Another thing, stay away from dbunit, it's a great framwork to start working, but it becomes hellish when a project becomes something more than tiny. My preference here, is to have a set of Test Data Builder classes to create the data, and insert it in the setup of the test or in the test itself.

And check dbmigrate, it's not for testing, but it will help you to manage scripts to upgrade and downgrade your DB schema.

In the scenario where the DB server is shared, I've creates one schema/user per environment. Since each developer has his own "local" environment, he also owns one schema.


Here are my answers :

  1. Use mock DAOs to test your services. Much easier, mush faster. Use EasyMock or Mockito or any other mock framework to test the service layer.
  2. Give each developer its own database schema to execute his tests. Such schemas are typically empty : the unit tests populate the database with a small test data set before running a test, and empties it once the test is completed. Use DBUnit for this.
  3. If the reads work against a well-defined, static, test data set (which you should unit-test), then you can rely on them to unit-test the writes. But you can also use ad-hoc queries or even DBUnit to test that the writes work as expected. The fact that the tests are not necessarily run in this order doesn't matter. If everything passes, then everything is OK.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜