Skip to content

Support @Transactional on TestNG @BeforeClass methods in the TestContext framework [SPR-11397] #16024

Closed
@spring-projects-issues

Description

@spring-projects-issues

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:

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions