Skip to content

Working with TestContainers

Somkiat Puisungnoen edited this page May 18, 2026 · 5 revisions

Working with TestContainers

  • Database with PostgreSQL

1. Add dependencies to project

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-testcontainers</artifactId>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.testcontainers</groupId>
	<artifactId>testcontainers-junit-jupiter</artifactId>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.testcontainers</groupId>
	<artifactId>testcontainers-postgresql</artifactId>
	<scope>test</scope>
</dependency>

2. Config database in file application.properties

# Driver spy tells Testcontainers to boot a Postgres container on demand
spring.datasource.url=jdbc:tc:postgresql:16-alpine:///demodb
spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver

# Credentials can be anything (Testcontainers bypasses authentication by default here)
spring.datasource.username=user
spring.datasource.password=test

# Standard JPA setup
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

3. Spring Boot Testing with TestContainers

  • PostgreSQL
  • Initial data for testing
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Testcontainers
class HelloIntegrationTest {

    @Container
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres");

    @Autowired
    private HelloService helloService;
    @Autowired
    private HelloRepository helloRepository;

    @Test
    void case01() {
        // Assert
        Hello h1 = new Hello("message 1");
        Hello h2 = new Hello("message 1");
        Hello h3 = new Hello("message 1");
        helloRepository.save(h1);
        helloRepository.save(h2);
        helloRepository.save(h3);
        // Act
        List<Hello> dataList = helloService.fetchFromDb();
        // Assert
        assertEquals(3, dataList.size());
    }

}

Entity class

@Entity
public class Hello {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String message;
...

4. Initial data for testing from file

  • schema.sql
  • data.sql

File application.properties

spring.sql.init.mode=always

File schema.sql

create table if not exists hello (
     id bigserial not null,
     message varchar not null
);

File data.sql

insert into hello (id, message) values (1, 'message 01');
insert into hello (id, message) values (2, 'message 02');
insert into hello (id, message) values (3, 'message 03');

Clone this wiki locally