DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

OrderHub Day 9: Integration Tests on Real Postgres With Testcontainers

OrderHub Day 9: stop testing against a fake database. Today's integration tests spin up a REAL PostgreSQL in Docker โ€” with Testcontainers โ€” and they actually ran: 10/10 green against Postgres 16.

๐Ÿณ See the container lifecycle: https://dev48v.infy.uk/orderhub/day9-testcontainers.html

Mock vs H2 vs the real thing

  • Mocks (Day 8) are fast but never prove your SQL/JPA mapping works.
  • H2 (in-memory) is a stand-in โ€” and subtle Postgres-only behavior (types, case-sensitivity, SQL dialect) slips right through.
  • Testcontainers boots an actual Postgres in Docker for the test, runs your real Flyway migrations, exercises real JDBC, then throws the container away. No shared test DB to pollute.

The setup

@SpringBootTest
@Testcontainers
class OrderApiIT {
  @Container static PostgreSQLContainer<?> db =
      new PostgreSQLContainer<>("postgres:16-alpine");

  @DynamicPropertySource
  static void props(DynamicPropertyRegistry r) {
    r.add("spring.datasource.url", db::getJdbcUrl);
    r.add("spring.datasource.username", db::getUsername);
    r.add("spring.datasource.password", db::getPassword);
  }
  // ... TestRestTemplate POST -> 201 -> GET -> 200, all on real Postgres
}
Enter fullscreen mode Exit fullscreen mode

@DynamicPropertySource wires the container's JDBC URL into Spring at runtime. One test proves controller โ†’ service โ†’ JPA โ†’ real Postgres end-to-end.

Worth knowing

ITs need Docker available (locally + in CI). Name them *IT and run them with failsafe, separate from fast unit tests.

๐Ÿ”จ Full walkthrough (deps โ†’ @Container โ†’ @DynamicPropertySource โ†’ full-stack IT) on the page: https://dev48v.infy.uk/orderhub/day9-testcontainers.html

OrderHub โ€” a production-grade Spring Boot backend, one feature a day.
๐ŸŒ https://dev48v.infy.uk ยท Code: https://github.com/dev48v/order-hub-from-zero

Top comments (0)