I think its common for database tests to include CRUD operations. So these functions modify the database making the expected vales change: eg. if I test that a SELECT returns 2 rows, if a delete test runs 1st, I might just get a failure. Similar to INSERT. JUnit doesn't appear to run tests as they are defined, making expected values hard.
If I have my database reinitialized at every test, it maybe overkill and slow. So how might I approach this problem?
By default, JUnit runs tests using a deterministic but unpredictable order (MethodSorters. DEFAULT). In most cases, that behavior is perfectly fine and acceptable.
A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.
Yes, as Steve Hall pointed out, using transactional tests solves the problem of database consistency between tests and test runs 100%. Spring offers very elaborate support for this type of tests (see transaction management in TestContext Framework) but it is not that difficult to implement without it.
Inside transactional tests that rollback their transaction at the end you are free to apply any CRUD operations to your data as long as they are part of the transaction initiated by the test. Then single rollback during test tear down eliminates all CRUD effects on the database.
You may want to look at something like DBUnit. If that doesn't fit your needs, then you could try wrapping your tests in database transactions. You could use the setup
and teardown
methods to start and rollback your transactions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With