Why roll back transactions in a Spring test environment?

Viewed 22

from spring doc:

One common issue in tests that access a real database is their effect on the state of the persistence store. Even when you use a development database, changes to the state may affect future tests. Also, many operations — such as inserting or modifying persistent data — cannot be performed (or verified) outside of a transaction.

The TestContext framework addresses this issue. By default, the framework creates and rolls back a transaction for each test. You can write code that can assume the existence of a transaction. If you call transactionally proxied objects in your tests, they behave correctly, according to their configured transactional semantics. In addition, if a test method deletes the contents of selected tables while running within the transaction managed for the test, the transaction rolls back by default, and the database returns to its state prior to execution of the test. Transactional support is provided to a test by using a PlatformTransactionManager bean defined in the test’s application context.

If you want a transaction to commit (unusual, but occasionally useful when you want a particular test to populate or modify the database), you can tell the TestContext framework to cause the transaction to commit instead of roll back by using the @Commit annotation.

How can we be certain that a transactional test was successful if the transaction is rolled back after it? Perhaps the test will be failed as a result of the transaction failing upon commit, for instance because of a violation of a SQL constraint (in relational databases transactions). or, am I missing something?

1 Answers

As per my understanding, by default transaction got roll-back so that state of database remains unchanged.

For cases like unique constraint violation, ideally you should be verifying exception message/code which your application is throwing other than verifying state of transaction in unit tests.

Please note, you don't require to verify if rollback actually rolling back transaction or not, but you need to verify if error is thrown from your application after constraint violation occurred. So your success criteria in this case is to check error is thrown after trying to insert duplicate record, and to check if error message which you have thrown from your method is correct.

For cases like update/insert to table, you can mark test case with explicit commit & verify it by executing select query within test; that will be your success criteria.

Related