views:

55

answers:

4

When I test DAO module in JUnit, an obvious problem is: how to recover testing data in database? For instance, a record should be deleted in both test methods testA() and testB(), that means precondition of both test methods need an existing record to be deleted. Then my strategy is inserting the record in setUp() method to recover data.

What’s your better solution? Or your practical idea in such case? Thanks

+2  A: 

I'd make a method called createRecord(). It may be a test-method as well. And whenever you need to create a record, call that method from your other test methods.

Bozho
+1  A: 

Bozho is correct, of course, but just to add a bit of detail:

If possible, unit tests set up their data before manipulating it, and then clean up after themselves. So ideally you would not be trampling on existing data (perhaps copied from production) for testing, but setting some up as part of the test; that's practically the only way you can be assured that your test will be testing what you intended.

Carl Smotricz
+2  A: 

Maybe DBUnit can help you out. It allows to have a TEST database in a predefined state before executing each test. Once it set upped, it's really easy to test database driven applications.

HeDinges
+1  A: 

A simple solution is to roll back the transaction after the test (for example in tearDown()). That way, the tests can make all the changes they like but they won't change the database (don't forget to turn autoCommit off for the connection).

There is a drawback, though: If a test fails, you can't peek at the database to figure out why. Therefore, most of my tests clean the database before they run and they use autoCommit so I can see the last state where it failed, run a fixed SQL query against the data, etc.

Aaron Digulla
'roll back' solution is cool!
卢声远 Shengyuan Lu