I would like to understand that if I annotate my junit class with @Transactional, Spring will create only one transaction which will be shared among my @Test methods and rolled back at the end. Whereas if instead I mark each single @Test with @Transactional, a new transaction will be created and rolled back on a @Test basis. I didn't quite find the expected behaviour in the official documentation (link).
2 Answers
Putting @Transactional on a class level is equivalent to putting it on each of the test methods.
I don't think there is an easy way of achieving your first scenario, ie, a single transaction for all the tests. I am not sure it would make much sense anyway since tests will be executed in a random order so you cannot rely on seeing each others modifications. Of course you can always explicitly call your methods from a single uber-test with a single transaction.
@Transactional at JUnit test case class level will start new transaction before each test method and roll it back afterwards.
You cannot easily start new transaction at the beginning of test class and keep it open for the whole class, at least Spring is not supporting this. Your first workaround would be to use @BeforeClass/@AfterClass pair, but they must be static thus you don't have access to transactional manager.
But first ask yourself a question, why do you want to do this? Sounds like one test depends on the output or database side effects of the other. This is a big anti-pattern in testing, not to mention JUnit does not guarantee the order in which test methods are executed. Maybe you just need a database setup before each test case? @Before and @After are executed within the context of Spring transaction, so you can use them there.