Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Database Testing and Ordering of Tests

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?

like image 500
Jiew Meng Avatar asked Apr 06 '12 03:04

Jiew Meng


People also ask

How are JUnit tests ordered?

By default, JUnit runs tests using a deterministic but unpredictable order (MethodSorters. DEFAULT). In most cases, that behavior is perfectly fine and acceptable.

What is the correct order of the unit test layout?

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.


2 Answers

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.

like image 57
topchef Avatar answered Oct 08 '22 04:10

topchef


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.

like image 1
MarkOfHall Avatar answered Oct 08 '22 05:10

MarkOfHall