Home > Blockchain >  Spring Boot Test not rolling back transactions (MS SQL Server, Spring Boot 2.7.5)
Spring Boot Test not rolling back transactions (MS SQL Server, Spring Boot 2.7.5)

Time:01-12

I am writing integration tests for a project with multiple datasources and want to test the repository and service layer. Problem is that the @Transactional annotation is not working and data inserted during tests is persisted.

This is a simple IT. I need to use @SpringBootTest instead of @DataJpaTest because multiple datasources are configured in a bean which handles assigning the right datasource to the correct repository.

@SpringBootTest(classes = { MyApp.class, TestSecurityConfiguration.class })
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("database-test")
@Transactional
@Rollback
public class MyIT {


    @Autowired
    ChannelRepository channelRepository;

    @Test
    public void testChannels() {

        Channel testChannel1 = new Channel();
        testChannel1.setDescription("Test Channel 1");
        channelRepository.save(testChannel1);

        Channel testChannel2 = new Channel();
        testChannel2.setDescription("Test Channel 2");
        channelRepository.save(testChannel2);

        Channel channel = channelRepository.findById(1).get();
        assertThat(channel).isNotNull();
    }

}

The dialect configured in the application.yml is "org.hibernate.dialect.SQLServer2012Dialect" and the database is our test database that runs on a dedicated server, not an embedded database.

The data is inserted without rollback.

CodePudding user response:

After looking at the JpaTransactionManager logs using:

logging:
  level:
    sql: DEBUG
    ROOT: DEBUG
    org.springframework.orm.jpa: DEBUG
    org.springframework.transaction: DEBUG

I saw that for each .save() call there was a new inner transaction. I tried to specify the transaction manager manually by passing the value to the @Transactional annotation and now it works. Looks like the DataSource beans are not picked up entirely correct. I got the idea based on this article where a ChainedTransactionManager is used for multiple datasources https://medium.com/preplaced/distributed-transaction-management-for-multiple-databases-with-springboot-jpa-and-hibernate-cde4e1b298e4

  • Related