-
Notifications
You must be signed in to change notification settings - Fork 38.9k
Description
Adib Saikali opened SPR-11397 and commented
When using the Spring TestContext Framework with TestNG it is not possible to annotate a TestNG @BeforeClass method with @Transactional and have it executed with a Spring-managed transaction, as depicted in the example below.
@ContextConfiguration("/test.xml")
public class TransactionalTest extends AbstractTransactionalTestNGSpringContextTests {
@BeforeClass
@Transactional
public void setupDB() {
// the following assert fails because there is no active transaction.
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue();
// do some stuff that needs a tx
}
}
With the current implementation of AbstractTransactionalTestNGSpringContextTests it is possible to refer to any autowired variable within an @BeforeClass method. It seems that by the the time @BeforeClass method is invoked Spring is fully initialized and therefore any @Transactional method should be working. It feels counter-intuitive that @Transactional and @BeforeClass in TestNG don't work with each other. As an aside, I understand why JUnit's @BeforeClass does not work with @Transactional.
One of the primary reasons for using TestNG over JUnit is that TestNG makes writing integration tests easier because of the way @BeforeClass works in TestNG. So in many integration testing scenarios it is possible that an @BeforeMethod method needs to read data from JPA or do some other prep work for the test that is @Transactional.
Can you please make @BeforeClass and @Transactional work together for TestNG?
In the meantime I have sent a pull request on GitHub to update the docs so that they at least warn users that @BeforeClass and @Transactional don't work with each other.
Affects: 3.0 GA
Issue Links:
- Execute all test methods in a class within the same transaction [SPR-5520] #10191 Execute all test methods in a class within the same transaction
- Improve documentation of transactional support in the TestContext framework [SPR-11399] #16026 Improve documentation of transactional support in the TestContext framework