Containers
A test of a repository wants the database the application will use, not a fake of it; a test of the security wants a Keycloak. With package:spring_boot_starter_test/containers.dart a test starts what it needs in Docker, the application is wired to it, and the containers are removed afterwards. It is Testcontainers with Spring Boot's @ServiceConnection.
Why
Fakes of a database pass tests that the real database fails: SQL dialects, constraints, transactions. A container gives the real thing, started fresh for the tests and removed after them, on a laptop and in CI alike.
Example
import 'package:spring_boot_starter_test/containers.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';
import 'spring_gen/book_repository.test.spring.dart';
@SpringBootTest()
@Testcontainers()
class BookRepositoryTest {
// Started once for the class, before its context, removed after it:
// its URL, user and password become spring.datasource.* of the context.
@Container()
@ServiceConnection()
static final postgres = PostgresContainer('postgres:17-alpine');
// Any image: wait for a log line, an HTTP answer or a port.
@Container()
static final redis = GenericContainer('redis:7.4-alpine')
.withExposedPorts([6379])
.waitingFor(Wait.forLogMessage('Ready to accept connections'));
// Runs when the context starts, after the containers did.
@DynamicPropertySource()
static void properties(DynamicPropertyRegistry registry) => registry.add(
'cache.redis.url',
() => 'redis://${redis.host}:${redis.mappedPort(6379)}',
);
@Autowired()
late BookRepository books;
@Test()
Future<void> savesAndFinds() async { /* ... */ }
}
void main() => runSpringTests();
containers.dart is a library of its own: it needs dart:io (nothing of it exists on the web), and its Container annotation would clash with Flutter's widget.
Containers of a test class
@Container()marks astaticfield holding aGenericContaineror a module. The containers start in the order of the fields, before the@BeforeAllmethods and the context, and are removed after the context closed and the@AfterAllmethods ran. Per-test containers are not supported.@ServiceConnection()puts the container's connection properties into the dynamic properties, which win overproperties:, the config files and the environment. A@DynamicPropertySourcemethod runs after them and can change one.@Testcontainers()is optional. It only sets what happens without Docker:@Testcontainers(disabledWithoutDocker: false)fails instead of skipping.- Without Docker the whole class is skipped, with the reason. With
CONTAINERS_REQUIRED=true(set it in CI) it fails instead. @DataTest(replaceDatabase: false)ofspring_boot_starter_datawith a@ServiceConnectionPostgresContainerruns the repository tests on that PostgreSQL, migrations applied and every test rolled back.
Modules and their connection properties
| Module | Defaults | @ServiceConnection sets |
|---|---|---|
PostgresContainer([image]) |
database, user and password test; withDatabaseName, withUsername, withPassword, withInitScript; jdbcUrl, url |
spring.datasource.url, spring.datasource.username, spring.datasource.password |
KeycloakContainer([image]) |
admin admin/admin; withAdminCredentials, withRealmImport(hostPath), withProviderId; issuerUri, authServerUrl |
spring.security.oauth2.resourceserver.jwt.issuer-uri, spring.security.oauth2.client.provider.<id>.issuer-uri |
| your own | anything: implement ServiceConnectionProperties (Map<String, String> get connectionProperties) |
GenericContainer
Any image. The methods return the container, so they chain (on a module, use cascades to keep its type):
| Method | Does |
|---|---|
withEnv(name, value), withEnvironment(map) |
Environment variables |
withCommand(list), withEntrypoint(list) |
Replace the image's command or entry point |
withExposedPorts([5432]) |
Publish the ports on random free ports of the host, on the loopback interface only |
withCopyFile(hostPath, containerPath), withCopyContent(text, containerPath) |
Files copied in before the start |
withLabel(name, value) |
A label |
withHealthCheck(['CMD-SHELL', 'pg_isready']) |
A health check for images without one |
waitingFor(strategy) |
When it counts as ready |
withStartupTimeout(duration) |
60 s by default; the image pull is not counted |
withReuse(true) |
Keep it for the next run (never in CI) |
withNetwork(network), withNetworkAliases(['db']) |
Put it on a Network of the run, where the other containers of it reach this one by these names and the ports it listens on. See Networks |
withExtraHost(host, address) |
A line of the container's hosts file; host-gateway is the machine the daemon runs on |
start() pulls the image when it is missing, creates the container, copies the files, starts it and waits; stop() removes it. host, mappedPort(5432), baseUrl(8080), getLogs() and execInContainer([...]) are there once it started. When it does not become ready, the container is removed and a ContainerLaunchException says why, with the last lines it printed.
Networks
A container reaches the host's published ports, not another container. For two that must talk (an API and its database), put them on a Network:
static final network = Network.newNetwork();
@Container()
static final database = PostgresContainer('postgres:17-alpine')
.withNetwork(network)
.withNetworkAliases(['db']);
@Container()
static final api = GenericContainer('postgrest/postgrest:v12.2.3')
.withNetwork(network)
.withEnv('PGRST_DB_URI', 'postgres://test:test@db:5432/test')
.withExposedPorts([3000]);
- Inside the network the database is
db:5432: its alias and the port it listens on. The test itself still usesmappedPort. - The network is created when its first container starts, and is removed with the run's containers (by the reaper too, when the process is killed).
network.close()removes it sooner. - A container kept with
withReusecannot be on one. - Under them,
DockerClienthascreateNetworkandremoveNetwork, andDockerContainerConfighasnetwork,networkAliasesandextraHosts.
Wait strategies
Wait. |
Ready when |
|---|---|
forListeningPort() (default) |
Every published port accepts a connection and keeps it |
forLogMessage(regex, times) |
A line of standard output or error matches |
forHttp(path) with .forStatusCode(200), .forPort(8080), .forStatusCodeMatching(...), .usingTls() |
An HTTP request answers |
forHealthcheck() |
The container's health check passes |
forAll([...]) |
All of them |
A container that exits while the strategy waits fails the start at once, with its exit code.
As functions
void main() {
final postgres = PostgresContainer();
final containers = TestContainers({'postgres': postgres},
serviceConnections: {'postgres'});
setUpAll(containers.start);
tearDownAll(containers.stop);
final app = springBootTest(
springApplication,
dynamicProperties: containers.registerConnections,
);
}
skip: TestContainers.skipReason() skips a group or test without Docker.
The Docker daemon
DockerClient speaks the Docker Engine API with dart:io, no package behind it. The daemon is found as the docker command finds it: DOCKER_HOST (unix:///path, tcp://host:2375), else the first of /var/run/docker.sock, ~/.docker/run/docker.sock (Docker Desktop), ~/.colima/default/docker.sock, ~/.rd/docker.sock (Rancher Desktop) and $XDG_RUNTIME_DIR/docker.sock. Windows' named pipe, TLS to a remote daemon and private registries are not supported yet (pull the image beforehand).
Cleanup and reuse
- Every container carries the labels
org.testcontainers=true,org.testcontainers.lang=dartandorg.testcontainers.sessionId=<run id>, and is removed bystop(). - If the process dies first (
kill -9, a crash), Testcontainers' reaper (testcontainers/ryuk:0.14.0) removes every container of the run ten seconds later.TESTCONTAINERS_RYUK_DISABLED=trueswitches it off;TESTCONTAINERS_RYUK_CONTAINER_IMAGEnames another image. withReuse(true)keeps a container for the next run, found by a hash of its configuration. It is ignored whenCIis set. Remove kept containers withdocker rm -f $(docker ps -aq --filter label=org.testcontainers.reuse.hash).
In Spring (Java)
@SpringBootTest
@Testcontainers
class BookRepositoryTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
}
Network.newNetwork(), withNetwork and withNetworkAliases are Testcontainers' names. Differences: containers.dart is its own import; @Container on static fields only; a class is skipped without Docker by default (Spring fails unless disabledWithoutDocker = true); no Docker Compose, no RedisContainer or MongoContainer; the fluent methods return GenericContainer (Dart has no self type).