Based on the documentation on Spring testing: https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions
Annotating a test method with @Transactional causes the test to be run within a transaction that is, by default, automatically rolled back after completion of the test. If a test class is annotated with @Transactional, each test method within that class hierarchy runs within a transaction. Test methods that are not annotated with @Transactional (at the class or method level) are not run within a transaction.
@Transactional
is needed in an integration test using Spring Test. This approach is good in that after the test all the update will be rolled back.
Question: But the approach of adding @Transactional
annotation to each test method doesn't test the persisted result. is this approach a true integration test at all?
1 Answer 1
But the approach of adding @Transactional annotation to each test method doesn't test the persisted result. is this approach a true integration test at all?
Testing the persisted result after the @Transactional annotation rolls the changes back doesn’t test your custom changes. That would test the @Transactional annotation and the roll back system. That was already tested by Spring and your DB respectively. Those tests don't need to be redone here.
In a way they can't be done here since many things can talk to the DB. There's no guaranty that the DB will be back in the same state as before your transaction since other updates may have happened by now. A rolled back transaction only promises that your changes are not applied. Not that nothing else changed.
-
thanks a lot for your answer. what did you mean "Those tests don't need to be redone here"? I previously wrote such integration test by retrieving the persisted result from the database and then verify the newly retrieved data, but wouldn't my approach be more viable?Rui– Rui2025年01月16日 16:39:26 +00:00Commented Jan 16 at 16:39
-
@Rui better now?candied_orange– candied_orange2025年01月16日 18:06:06 +00:00Commented Jan 16 at 18:06
Explore related questions
See similar questions with these tags.
@Transactional
annotation to the@Test
method, but in this case is the test an integration test since the test is testing only one class, i.e. the DAO class