M03 Q19 What is the default rollback policy in a JUnit test and annotate your @Test annotated method with @Transactional?
What is the default rollback policy in a JUnit test, when you use the @RunWith(SpringJUnit4ClassRunner.class) in JUnit 4 or @ExtendWith(SpringExtension.class) in JUnit 5, and annotate your @Test annotated method with @Transactional?
Default rollback policy in @Test methods annotated with @Transactional is always rollback. This means that after test execution transaction will always be rolled back. The reason for this is that each test method should be able to change state of database or call other classes that will change state of the database, however for the tests to be repeatable, changes should be reverted after @Test method execution.
You can change this behavior by using @Rollback annotation set to false.
Let's look into the code and define how it works. Firstly, business logic implementation.
We have EmployeeService and one method that is annotated with @Transactional annotation. That means that at the begging of the execution of this method the transaction will be started. And after finishing the execution the transaction will be committed.
Also, we have a test with two methods. The first method is called shouldRollbackTransaction and it is annotated with @Transactional. And the default behavior for the test is after execution of this method the transaction will be rolled back.
The second example is exactly the same. The difference only in rollback policy is set to false. So we will use not default rollback policy. And at the end of the execution transaction will be committed.