views:

612

answers:

2

I have a simple CRUD operations that needs to be unit tested These test cases are for DAO layer- so all tests are against the database and hence cant be mocked.

So I have one test cases for create another for update and another for read.

1) Should I hard code the data in the JUnit class or do you externalize it ?

2) The Read TestCase would obviously need data in the database. Should I depend upon the Create Test cases to set up the data or use a SQL statement for that ?

what is the best-practice on this?

If you can point me to an internet resource which discusses this- that would be great.

Thanks !!!

+3  A: 

Spring has excellent support for this sort of thing - unit tests that you want to operate against a "test" database, which can be scripted to be re-created on each individual unit test.

The latter part of that last sentence is the key to developing re-usable and extensible unit tests - a unit test against a database should not be forced to rely on the data optimistically being in a certain state, or rely on a previous unit test to run first - you'll want to re-create the database for each unit test so that each test case gets a "clean" version of the data.

The step-by-step tutorial on setting up Spring MVC actually has a section on setting up unit tests for database classes, which I think would be a valuable reference even when you are not using Spring MVC - you can use this as a reference on how to set up the test database to be created/initialized from the build script, using the Spring container to re-load the data on each test run, etc.

matt b
+2  A: 

I'd recommend using DBUnit. Allows you to setup a database to a known state using files and has nice comparison with expected results functionality. Getting started guide is here.

It's also good practice not perform any commits as part of the testcase and then you can rollback on tearDown().

Peter