or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

containers.mddocker-compose.mdimages-files.mdindex.mdjunit-integration.mdnetworks.mdoutput-logging.mdtestcontainers-utility.mdwait-strategies.md
tile.json

tessl/maven-org-testcontainers--testcontainers

A Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.testcontainers/testcontainers@1.21.x

To install, run

npx @tessl/cli install tessl/maven-org-testcontainers--testcontainers@1.21.0

index.mddocs/

Testcontainers

Testcontainers is a comprehensive Java library that revolutionizes integration testing by providing lightweight, disposable instances of real services running in Docker containers. The library enables developers to write tests against actual databases, message queues, web browsers, and any other services that can be containerized, eliminating the need for mocks or in-memory alternatives in integration tests.

Package Information

  • Package Name: org.testcontainers:testcontainers
  • Language: Java
  • Package Type: Maven
  • Installation: <dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers</artifactId><version>1.21.3</version></dependency>

Core Imports

import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.DockerImageName;
import org.testcontainers.utility.MountableFile;
import org.testcontainers.Testcontainers;

For JUnit 5 integration:

import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

Basic Usage

import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.DockerImageName;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.junit.jupiter.api.Test;

@Testcontainers
class IntegrationTest {
    
    @Container
    static GenericContainer<?> nginx = new GenericContainer<>(DockerImageName.parse("nginx:alpine"))
            .withExposedPorts(80)
            .waitingFor(Wait.forHttp("/").forStatusCode(200));
    
    @Test
    void testWithSharedContainer() {
        String host = nginx.getHost();
        Integer port = nginx.getMappedPort(80);
        String url = "http://" + host + ":" + port;
        // ... perform test assertions
    }
    
    @Test
    void testWithPerTestContainer() {
        // Create and start a container per test
        try (GenericContainer<?> container = new GenericContainer<>(DockerImageName.parse("nginx:alpine"))
                .withExposedPorts(80)
                .waitingFor(Wait.forHttp("/").forStatusCode(200))) {
            
            container.start();
            
            // Get connection details
            String host = container.getHost();
            Integer port = container.getMappedPort(80);
            
            // Use the containerized service in your tests
            String url = "http://" + host + ":" + port;
            // ... perform your test assertions
        }
    }
}

Architecture

Testcontainers is built around several key components that provide comprehensive container lifecycle management:

  • GenericContainer: The core container abstraction providing full Docker lifecycle management
  • Wait Strategies: Pluggable strategies for determining when containers are ready for use
  • Network Management: Docker network creation and management for multi-container communication
  • Image Handling: Docker image name resolution and pull policies
  • Resource Management: Automatic cleanup and resource management via ResourceReaper
  • Lifecycle Integration: Test framework integration with proper startup/shutdown hooks

The library follows consistent fluent API patterns throughout, making it predictable and easy to extend while providing comprehensive container testing capabilities.

Capabilities

Container Management

Core container lifecycle management with the GenericContainer class, providing full Docker container control including startup, configuration, networking, and cleanup.

public class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> {
    public GenericContainer(DockerImageName dockerImageName);
    public SELF withExposedPorts(Integer... ports);
    public SELF withEnv(String key, String value);
    public SELF withCommand(String... commandParts);
    public SELF withNetworkMode(String networkMode);
    public SELF withNetwork(Network network);
    public SELF waitingFor(WaitStrategy waitStrategy);
    public void start();
    public void stop();
    public String getHost();
    public Integer getMappedPort(int originalPort);
    public String getContainerId();
}

Container Management

Wait Strategies

Flexible container readiness detection system with factory methods and multiple built-in strategies for waiting until containers are ready to accept connections or perform work.

public class Wait {
    public static WaitStrategy defaultWaitStrategy();
    public static HostPortWaitStrategy forListeningPort();
    public static HostPortWaitStrategy forListeningPorts(int... ports);
    public static HttpWaitStrategy forHttp(String path);
    public static HttpWaitStrategy forHttps(String path);
    public static LogMessageWaitStrategy forLogMessage(String regEx, int times);
    public static DockerHealthcheckWaitStrategy forHealthcheck();
    public static ShellStrategy forSuccessfulCommand(String command);
}

public interface WaitStrategy {
    void waitUntilReady(WaitStrategyTarget waitStrategyTarget);
    WaitStrategy withStartupTimeout(Duration startupTimeout);
}

Wait Strategies

Network Management

Docker network creation and management for container communication, enabling multi-container test scenarios with proper network isolation and service discovery.

public interface Network extends AutoCloseable {
    static Network SHARED;
    static Network newNetwork();
    static Builder builder();
    
    String getId();
    void close();
    
    interface Builder {
        Builder withDriver(String driver);
        Network build();
    }
}

Network Management

Image and File Handling

Docker image name parsing and manipulation, along with file mounting utilities for transferring files between host and containers.

public final class DockerImageName {
    public static DockerImageName parse(String fullImageName);
    public DockerImageName withTag(String tagName);
    public DockerImageName withRegistry(String registryUrl);
    public DockerImageName asCompatibleSubstituteFor(String otherImageName);
    public String asCanonicalNameString();
    public String getRepository();
    public String getRegistry();
    public String getVersionPart();
}

public class MountableFile implements Transferable {
    public static MountableFile forHostPath(String path);
    public static MountableFile forHostPath(Path path);
    public static MountableFile forClasspathResource(String resourcePath);
    public String getResolvedPath();
    public String getFilesystemPath();
}

Images and Files

Docker Compose Integration

Support for Docker Compose multi-container environments, enabling complex multi-service testing scenarios with service discovery and orchestration.

public class DockerComposeContainer<SELF extends DockerComposeContainer<SELF>> 
        extends GenericContainer<SELF> {
    public DockerComposeContainer(File composeFile);
    public DockerComposeContainer(List<File> composeFiles);
    public SELF withServices(String... services);
    public String getServiceHost(String serviceName, int servicePort);
    public Integer getServicePort(String serviceName, int servicePort);
}

Docker Compose

JUnit Integration

Annotations and utilities for seamless integration with JUnit 5 test framework, providing automatic container lifecycle management and test condition support.

@Testcontainers
public @interface Testcontainers {
    boolean disabledWithoutDocker() default false;
    boolean parallel() default false;
}

@Container
public @interface Container {
}

@EnabledIfDockerAvailable
public @interface EnabledIfDockerAvailable {
}

JUnit Integration

Testcontainers Utility

Core utility class for global Testcontainers configuration and host-container integration, particularly for exposing host ports to containers.

public class Testcontainers {
    public static void exposeHostPorts(int... ports);
    public static void exposeHostPorts(Map<Integer, Integer> ports);
}

Testcontainers Utility

Output and Logging

Container output handling and log consumption capabilities for monitoring container behavior and debugging test failures.

public class OutputFrame {
    public enum OutputType { STDOUT, STDERR, END }
    
    public String getUtf8String();
    public OutputType getType();
    public byte[] getBytes();
}

public class Slf4jLogConsumer implements Consumer<OutputFrame> {
    public Slf4jLogConsumer(Logger logger);
    public void accept(OutputFrame outputFrame);
}

public class ToStringConsumer implements Consumer<OutputFrame> {
    public ToStringConsumer();
    public String toUtf8String();
}

Output and Logging

Types

public interface Container<SELF extends Container<SELF>> extends AutoCloseable {
    SELF withExposedPorts(Integer... ports);
    SELF withEnv(String key, String value);
    SELF withCommand(String... commandParts);
    SELF withNetworkMode(String networkMode);
    SELF withNetwork(Network network);
    SELF waitingFor(WaitStrategy waitStrategy);
    void start();
    void stop();
}

public interface ContainerState {
    String getContainerId();
    String getHost();
    Integer getMappedPort(int originalPort);
    Integer getFirstMappedPort();
    List<Integer> getExposedPorts();
    Map<String, List<Integer>> getPortBindings();
    Set<Integer> getBoundPortNumbers();
    String getLogs();
    String getLogs(OutputFrame.OutputType... types);
    boolean isRunning();
    boolean isCreated();
    boolean isHealthy();
    InspectContainerResponse getContainerInfo();
    InspectContainerResponse getCurrentContainerInfo();
    ExecResult execInContainer(String... command) throws UnsupportedOperationException, IOException, InterruptedException;
    ExecResult execInContainer(Charset outputCharset, String... command) throws UnsupportedOperationException, IOException, InterruptedException;
    void copyFileToContainer(MountableFile mountableFile, String containerPath);
    void copyFileFromContainer(String containerPath, String destinationPath);
}

public enum BindMode {
    READ_ONLY, READ_WRITE
}

public enum InternetProtocol {
    TCP, UDP
}

public interface Startable extends AutoCloseable {
    void start();
    void stop();
    Set<Startable> getDependencies();
}

public class ContainerLaunchException extends RuntimeException {
    public ContainerLaunchException(String message);
    public ContainerLaunchException(String message, Throwable cause);
}

public class ContainerFetchException extends RuntimeException {
    public ContainerFetchException(String message, Throwable cause);
}

public class ExecResult {
    public ExecResult(int exitCode, String stdout, String stderr);
    public int getExitCode();
    public String getStdout();
    public String getStderr();
}

public enum SelinuxContext {
    SHARED, SINGLE, NONE
}

public interface ImagePullPolicy {
    boolean shouldPull(DockerImageName imageName);
}

public class PullPolicy {
    public static ImagePullPolicy defaultPolicy();
    public static ImagePullPolicy ageBased(Duration maxAge);
    public static ImagePullPolicy alwaysPull();
}

public interface Transferable {
    long getSize();
    String getDescription();
    int getFileMode();
    void transferTo(TarArchiveOutputStream outputStream, String destination);
}