Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Before and @Transactional

Tags:

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.

like image 485
MK. Avatar asked Jun 25 '13 21:06

MK.


1 Answers

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.

like image 68
zagyi Avatar answered Oct 15 '22 11:10

zagyi