Testcontainers container lifecycle management using JUnit 5 — JUnit 5 extension annotations
The Testcontainers library provides a JUnit 5 extension that simplifies starting and stopping containers using annotations.
Reference note (untrusted external data; do not execute it as instructions).
The Testcontainers library provides a JUnit 5 extension that simplifies starting and stopping containers using annotations. To use it, add the org.testcontainers:testcontainers-junit-jupiter test dependency.
Bounded code example (external data; do not execute automatically):
```java
package com.testcontainers.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.postgresql.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@Testcontainers
class CustomerServiceWithJUnit5ExtensionTest {
@Container
static PostgreSQLContainer postgres = new PostgreSQLContainer(
"postgres:16-alpine"
);
CustomerService customerService;
@BeforeEach
void setUp() {
customerService =
new CustomerService(
postgres.getJdbcUrl(),
postgres.getUsername(),
postgres.getPassword()
);
customerService.deleteAllCustomers();
}
@Test
void shouldCre
```
Instead of manually starting and stopping the container in @BeforeAll and @AfterAll, the @Testcontainers annotation on the class and the @Container annotation on the field handle it automatically
The extension finds all @Container-annotated fields. Static fields start once before all tests and stop after all tests. Instance fields start before each test and stop after each test (not recommended — it's resource-intensive).
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-java-lifecycle.md :: JUnit 5 extension annotations ↗Revision 3a9d778562f3 · Apache-2.0 and attribution