Video in progress

Strong Middle 🌱 Spring

Why is Testcontainers better than H2 for integration tests, and how do you wire it into Spring Boot?

H2 only imitates PostgreSQL: the SQL dialect, types, indexes and locking behavior are different, so the test is green and prod breaks. Testcontainers starts a real database in Docker, and in Boot 3.1+ @ServiceConnection configures the connection automatically.

📖 Answer

@SpringBootTest
@Testcontainers
class OrderRepositoryIT {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired OrderRepository orders;

    @Test
    void findsPaidOrdersWithJsonbFilter() {
        // native query with a jsonb operator — wouldn't work on H2 at all
    }
}

@ServiceConnection passes the container's URL, username and password into spring.datasource.* for you — no need to write @DynamicPropertySource.

To keep tests fast:

  • make the container static — it starts once per class;
  • share one container across several test classes with a common base class or @ImportTestcontainers;
  • for local runs, set testcontainers.reuse.enable=true.

Since Boot 3.1 you can use this in dev too: a TestApplication class starts the app against the database in Testcontainers, so nobody has to install PostgreSQL on their own machine.

CI needs Docker. For places where it isn't available, separate these tests with their own profile or tag.