I have
@RunWith(SpringJUnit4ClassRunner.class) @TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager") @Before @Transactional public void mySetup() { // insert some records in db } @After @Transactional public void myTeardown() { // delete some records } @Test @Transactional public void testMy() { // do stuff }
My question is: will mySetup, testMy and myTeardown all run within the same transaction? It seems like they should, but I'm getting some strange error which might suggest that they are stepping on each other.
Yes, all three methods will run within the same transaction. See section TestContext Framework/Transaction management in the reference docs:
Any before methods (such as methods annotated with JUnit's @Before) and any after methods (such as methods annotated with JUnit's @After) are executed within a transaction
Thus the @Transactional
annotation on mySetup()
and myTeardown()
is kind of redundant, or might be even considered misleading, as their transactionality is determined by the individual test method being currently executed.
This is because the beforeTestMethod()
and afterTestMethod()
callbacks of TransactionalTestExecutionListener
(responsible for starting/completing the transaction) are executed before JUnit's @Before
and after JUnit's @After
methods, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With