Skip to content
Fresh

Container lifecycle (Java)

Back

Guides

Testcontainers container lifecycle management using JUnit 5

Learn different approaches to manage container lifecycle with Testcontainers using JUnit 5 lifecycle callbacks, extension annotations, and the singleton containers pattern.

Java Testing with Docker

20 minutes

1

Create the project

2

Lifecycle callbacks

3

Extension annotations

4

Singleton containers

« Back to all guides

Testcontainers container lifecycle management using JUnit 5

Table of contents


Learn different approaches to manage container lifecycle with Testcontainers using JUnit 5 lifecycle callbacks, extension annotations, and the singleton containers pattern.

Time to complete20 minutes

In this guide, you will learn how to:

  • Start and stop containers using JUnit 5 lifecycle callbacks
  • Manage containers using JUnit 5 extension annotations (@Testcontainers and @Container)
  • Share containers across multiple test classes using the singleton containers pattern
  • Avoid a common misconfiguration when combining extension annotations with singleton containers

Prerequisites

  • Java 17+
  • Your preferred IDE
  • A Docker environment supported by Testcontainers

Note

If you're new to Testcontainers, visit the Testcontainers overview to learn more about Testcontainers and the benefits of using it.

Modules

  1. Create the project Set up a Java project with a PostgreSQL-backed customer service for lifecycle testing.

  2. Lifecycle callbacks Manage Testcontainers container lifecycle using JUnit 5 @BeforeAll and @AfterAll callbacks.

  3. Extension annotations Manage Testcontainers container lifecycle using @Testcontainers and @Container annotations.

  4. Singleton containers Share containers across multiple test classes using the singleton containers pattern.