or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# Testcontainers

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: org.testcontainers:testcontainers

7

- **Language**: Java

8

- **Package Type**: Maven

9

- **Installation**: `<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers</artifactId><version>1.21.3</version></dependency>`

10

11

## Core Imports

12

13

```java

14

import org.testcontainers.containers.GenericContainer;

15

import org.testcontainers.containers.Network;

16

import org.testcontainers.containers.wait.strategy.Wait;

17

import org.testcontainers.utility.DockerImageName;

18

import org.testcontainers.utility.MountableFile;

19

import org.testcontainers.Testcontainers;

20

```

21

22

For JUnit 5 integration:

23

24

```java

25

import org.testcontainers.junit.jupiter.Container;

26

import org.testcontainers.junit.jupiter.Testcontainers;

27

```

28

29

## Basic Usage

30

31

```java

32

import org.testcontainers.containers.GenericContainer;

33

import org.testcontainers.containers.wait.strategy.Wait;

34

import org.testcontainers.utility.DockerImageName;

35

import org.testcontainers.junit.jupiter.Container;

36

import org.testcontainers.junit.jupiter.Testcontainers;

37

import org.junit.jupiter.api.Test;

38

39

@Testcontainers

40

class IntegrationTest {

41

42

@Container

43

static GenericContainer<?> nginx = new GenericContainer<>(DockerImageName.parse("nginx:alpine"))

44

.withExposedPorts(80)

45

.waitingFor(Wait.forHttp("/").forStatusCode(200));

46

47

@Test

48

void testWithSharedContainer() {

49

String host = nginx.getHost();

50

Integer port = nginx.getMappedPort(80);

51

String url = "http://" + host + ":" + port;

52

// ... perform test assertions

53

}

54

55

@Test

56

void testWithPerTestContainer() {

57

// Create and start a container per test

58

try (GenericContainer<?> container = new GenericContainer<>(DockerImageName.parse("nginx:alpine"))

59

.withExposedPorts(80)

60

.waitingFor(Wait.forHttp("/").forStatusCode(200))) {

61

62

container.start();

63

64

// Get connection details

65

String host = container.getHost();

66

Integer port = container.getMappedPort(80);

67

68

// Use the containerized service in your tests

69

String url = "http://" + host + ":" + port;

70

// ... perform your test assertions

71

}

72

}

73

}

74

```

75

76

## Architecture

77

78

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

79

80

- **GenericContainer**: The core container abstraction providing full Docker lifecycle management

81

- **Wait Strategies**: Pluggable strategies for determining when containers are ready for use

82

- **Network Management**: Docker network creation and management for multi-container communication

83

- **Image Handling**: Docker image name resolution and pull policies

84

- **Resource Management**: Automatic cleanup and resource management via ResourceReaper

85

- **Lifecycle Integration**: Test framework integration with proper startup/shutdown hooks

86

87

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

88

89

## Capabilities

90

91

### Container Management

92

93

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

94

95

```java { .api }

96

public class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> {

97

public GenericContainer(DockerImageName dockerImageName);

98

public SELF withExposedPorts(Integer... ports);

99

public SELF withEnv(String key, String value);

100

public SELF withCommand(String... commandParts);

101

public SELF withNetworkMode(String networkMode);

102

public SELF withNetwork(Network network);

103

public SELF waitingFor(WaitStrategy waitStrategy);

104

public void start();

105

public void stop();

106

public String getHost();

107

public Integer getMappedPort(int originalPort);

108

public String getContainerId();

109

}

110

```

111

112

[Container Management](./containers.md)

113

114

### Wait Strategies

115

116

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.

117

118

```java { .api }

119

public class Wait {

120

public static WaitStrategy defaultWaitStrategy();

121

public static HostPortWaitStrategy forListeningPort();

122

public static HostPortWaitStrategy forListeningPorts(int... ports);

123

public static HttpWaitStrategy forHttp(String path);

124

public static HttpWaitStrategy forHttps(String path);

125

public static LogMessageWaitStrategy forLogMessage(String regEx, int times);

126

public static DockerHealthcheckWaitStrategy forHealthcheck();

127

public static ShellStrategy forSuccessfulCommand(String command);

128

}

129

130

public interface WaitStrategy {

131

void waitUntilReady(WaitStrategyTarget waitStrategyTarget);

132

WaitStrategy withStartupTimeout(Duration startupTimeout);

133

}

134

```

135

136

[Wait Strategies](./wait-strategies.md)

137

138

### Network Management

139

140

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

141

142

```java { .api }

143

public interface Network extends AutoCloseable {

144

static Network SHARED;

145

static Network newNetwork();

146

static Builder builder();

147

148

String getId();

149

void close();

150

151

interface Builder {

152

Builder withDriver(String driver);

153

Network build();

154

}

155

}

156

```

157

158

[Network Management](./networks.md)

159

160

### Image and File Handling

161

162

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

163

164

```java { .api }

165

public final class DockerImageName {

166

public static DockerImageName parse(String fullImageName);

167

public DockerImageName withTag(String tagName);

168

public DockerImageName withRegistry(String registryUrl);

169

public DockerImageName asCompatibleSubstituteFor(String otherImageName);

170

public String asCanonicalNameString();

171

public String getRepository();

172

public String getRegistry();

173

public String getVersionPart();

174

}

175

176

public class MountableFile implements Transferable {

177

public static MountableFile forHostPath(String path);

178

public static MountableFile forHostPath(Path path);

179

public static MountableFile forClasspathResource(String resourcePath);

180

public String getResolvedPath();

181

public String getFilesystemPath();

182

}

183

```

184

185

[Images and Files](./images-files.md)

186

187

### Docker Compose Integration

188

189

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

190

191

```java { .api }

192

public class DockerComposeContainer<SELF extends DockerComposeContainer<SELF>>

193

extends GenericContainer<SELF> {

194

public DockerComposeContainer(File composeFile);

195

public DockerComposeContainer(List<File> composeFiles);

196

public SELF withServices(String... services);

197

public String getServiceHost(String serviceName, int servicePort);

198

public Integer getServicePort(String serviceName, int servicePort);

199

}

200

```

201

202

[Docker Compose](./docker-compose.md)

203

204

### JUnit Integration

205

206

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

207

208

```java { .api }

209

@Testcontainers

210

public @interface Testcontainers {

211

boolean disabledWithoutDocker() default false;

212

boolean parallel() default false;

213

}

214

215

@Container

216

public @interface Container {

217

}

218

219

@EnabledIfDockerAvailable

220

public @interface EnabledIfDockerAvailable {

221

}

222

```

223

224

[JUnit Integration](./junit-integration.md)

225

226

### Testcontainers Utility

227

228

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

229

230

```java { .api }

231

public class Testcontainers {

232

public static void exposeHostPorts(int... ports);

233

public static void exposeHostPorts(Map<Integer, Integer> ports);

234

}

235

```

236

237

[Testcontainers Utility](./testcontainers-utility.md)

238

239

### Output and Logging

240

241

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

242

243

```java { .api }

244

public class OutputFrame {

245

public enum OutputType { STDOUT, STDERR, END }

246

247

public String getUtf8String();

248

public OutputType getType();

249

public byte[] getBytes();

250

}

251

252

public class Slf4jLogConsumer implements Consumer<OutputFrame> {

253

public Slf4jLogConsumer(Logger logger);

254

public void accept(OutputFrame outputFrame);

255

}

256

257

public class ToStringConsumer implements Consumer<OutputFrame> {

258

public ToStringConsumer();

259

public String toUtf8String();

260

}

261

```

262

263

[Output and Logging](./output-logging.md)

264

265

## Types

266

267

```java { .api }

268

public interface Container<SELF extends Container<SELF>> extends AutoCloseable {

269

SELF withExposedPorts(Integer... ports);

270

SELF withEnv(String key, String value);

271

SELF withCommand(String... commandParts);

272

SELF withNetworkMode(String networkMode);

273

SELF withNetwork(Network network);

274

SELF waitingFor(WaitStrategy waitStrategy);

275

void start();

276

void stop();

277

}

278

279

public interface ContainerState {

280

String getContainerId();

281

String getHost();

282

Integer getMappedPort(int originalPort);

283

Integer getFirstMappedPort();

284

List<Integer> getExposedPorts();

285

Map<String, List<Integer>> getPortBindings();

286

Set<Integer> getBoundPortNumbers();

287

String getLogs();

288

String getLogs(OutputFrame.OutputType... types);

289

boolean isRunning();

290

boolean isCreated();

291

boolean isHealthy();

292

InspectContainerResponse getContainerInfo();

293

InspectContainerResponse getCurrentContainerInfo();

294

ExecResult execInContainer(String... command) throws UnsupportedOperationException, IOException, InterruptedException;

295

ExecResult execInContainer(Charset outputCharset, String... command) throws UnsupportedOperationException, IOException, InterruptedException;

296

void copyFileToContainer(MountableFile mountableFile, String containerPath);

297

void copyFileFromContainer(String containerPath, String destinationPath);

298

}

299

300

public enum BindMode {

301

READ_ONLY, READ_WRITE

302

}

303

304

public enum InternetProtocol {

305

TCP, UDP

306

}

307

308

public interface Startable extends AutoCloseable {

309

void start();

310

void stop();

311

Set<Startable> getDependencies();

312

}

313

314

public class ContainerLaunchException extends RuntimeException {

315

public ContainerLaunchException(String message);

316

public ContainerLaunchException(String message, Throwable cause);

317

}

318

319

public class ContainerFetchException extends RuntimeException {

320

public ContainerFetchException(String message, Throwable cause);

321

}

322

323

public class ExecResult {

324

public ExecResult(int exitCode, String stdout, String stderr);

325

public int getExitCode();

326

public String getStdout();

327

public String getStderr();

328

}

329

330

public enum SelinuxContext {

331

SHARED, SINGLE, NONE

332

}

333

334

public interface ImagePullPolicy {

335

boolean shouldPull(DockerImageName imageName);

336

}

337

338

public class PullPolicy {

339

public static ImagePullPolicy defaultPolicy();

340

public static ImagePullPolicy ageBased(Duration maxAge);

341

public static ImagePullPolicy alwaysPull();

342

}

343

344

public interface Transferable {

345

long getSize();

346

String getDescription();

347

int getFileMode();

348

void transferTo(TarArchiveOutputStream outputStream, String destination);

349

}

350

```