Integration tests on JPA repositories

Configuration

First add the corresponding dependencies in the pom.xml:

<dependencies>
    <!-- other dependencies -->
 
    <!-- TEST -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- embedded database for faster tests -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Create the integration test with the right annotations:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = DevicePairingJpaRepositoryIT.TestConfig.class)
@DataJpaTest
class DevicePairingJpaRepositoryIT {
 
    // need to create custom configuration so only use the right
    // spring-boot configuration
    @AutoConfigureTestDatabase
    @Configuration
    @EnableJpaRepositories(basePackages = "com.bioserenity.pairing.repository")
    @EntityScan
    static class TestConfig {
    }
 
    @Autowired
    private DevicePairingJpaRepository devicePairingJpaRepository;
 
    @Test
    void itWorks() {
        assertNotNull(devicePairingJpaRepository);
    }
}
title: By default, transactions in tests are rollbacked

By default, the transactions in the tests are rollbacked.

When testing the JPA methods, I got the following message “Rolled back transaction for test”.

I think it’s because it’s a test, so it will always rollback as to have isolated tests, so it’s not an issue.

If you want to disable auto rollback, just add the annotation @Rollback(false), e.g. on class level:

@DataJpaTest
@Rollback(false)
class FoobarIT {}

Or on method level:

@Test
@Rollback(false)
void testFoobar() {}

Resources