开发者

What’s the strategy to recover data during DAO unit test?

开发者 https://www.devze.com 2022-12-25 14:32 出处:网络
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 precondit

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 existi开发者_如何学运维ng 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


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.


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.


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.


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.

0

精彩评论

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