Testcontainers for Cassandra and MongoDB in Java Integration Tests
Integration tests that touch a real datastore tend to be where a project's build becomes unpredictable. A service that writes to Cassandra or MongoDB needs somewhere to write to, and the usual answers — a shared staging instance, a developer's locally installed database, or an embedded engine — each trade away something that matters later: repeatability, isolation, or confidence that the code works against the engine it will actually meet in production.
Testcontainers turns that trade-off around. It starts a real Cassandra node or MongoDB server in Docker, wires the mapped port into your application context, and shuts the container down when the test class finishes. What follows covers the parts that are not obvious: waiting strategies, replica-set configuration, seeding data that resembles production without importing production records, and keeping the whole thing fast enough that nobody starts skipping integration tests.
Why local containers beat shared test databases
A shared database server looks efficient on paper: one machine, one schema, many test runs. In practice the schema drifts as branches merge, rows left behind by yesterday's failure make today's assertions fail for reasons unrelated to the code, and two developers working on separate features cannot run their suites at the same time. Shared instances also accumulate genuine customer records copied from production, which is exactly the exposure the Australian Privacy Act 1988 and the Australian Privacy Principles were written to discourage.
Per-test containers invert that. Each test class gets its own Cassandra node or MongoDB server with an empty data directory, so a failure points at code rather than at residue. For the Java teams at Atlassian and Canva in Sydney, or REA Group in Melbourne, whose services lean heavily on wide-column and document stores, that isolation is the difference between a suite people trust and a suite people run with -DskipITs.
The honest caveats: Docker must be available on the machine or the runner, the first run pays for a multi-gigabyte image pull, and a Cassandra node wants more memory than most laptops will spare for a background process. None of that argues for going back to a shared box; it argues for caching images, capping heaps, and measuring timings on your own hardware rather than trusting generic advice.
Bringing a Cassandra node up inside the test lifecycle
Add the Testcontainers JUnit Jupiter dependency and the Cassandra module, and a test class takes a familiar shape. A static container field annotated with @Container starts before the class and stops afterwards, and a wait strategy blocks until the log announces the node has finished booting, avoiding the classic race where the driver connects to a port that is listening but not yet ready to serve CQL.
Wiring it into Spring Boot takes one more piece. Rather than hard-coding a host and port, expose a DynamicPropertySource that reads the container's mapped port and feeds spring.data.cassandra.contact-points and spring.data.cassandra.port, so the application connects to a throwaway node on localhost. MongoDB has a shortcut here: Spring Boot 3.1 and later can register the container for you with @ServiceConnection.
Schema setup belongs in the test code too. Create the keyspace and tables in a @BeforeAll block with the DataStax Java driver — CREATE KEYSPACE IF NOT EXISTS with a replication factor of one is plenty for tests — or point Spring Boot at a schema script. Keeping it in code puts setup next to the assertions and lets you vary the schema per scenario, such as a table with a clustering key to exercise partition behaviour.
Running MongoDB with realistic replica-set behaviour
The MongoDB container starts quickly, exposes the usual port, and works with spring-data-mongodb the way the Cassandra container works with Spring Data Cassandra: point the connection string at the mapped port and let the context wire itself. For plain CRUD and query tests, that is all you need.
Transactions and change streams are not. A standalone mongod cannot commit a multi-document transaction, so if the code under test relies on sessions with transactions, start the container with the replica-set command-line argument and then initiate the set from the client with a runCommand against the admin database. The extra second or two is worth it, because a test that passes against a standalone server can fail in production where the same operation runs inside a replica set.
Seeding MongoDB reads well with a MongoTemplate and a handful of Jackson-mapped fixture classes: insert a few realistic documents, create the indexes the application declares, and give any unique constraint a deterministic value, so a rerun produces the same duplicate-key failure rather than a random one. The two engines differ enough that it is worth setting them side by side before tuning either:
| Aspect | Cassandra | MongoDB |
|---|---|---|
| Typical image | cassandra:4.1 |
mongodb:7.0 |
| Port | 9042 | 27017 |
| Readiness signal | Log line announcing startup completion | Connection log, plus rs.initiate() when a replica set is required |
| Data setup | CQL scripts run through the Java driver | MongoTemplate inserts or Jackson-mapped fixtures |
| Extra configuration | Single-node cluster, replication factor 1 | Replica set with rs.initiate() for sessions and transactions |
| Spring Boot wiring | DynamicPropertySource for contact points and port |
@ServiceConnection or a dynamic connection string |
Seeding data and taming the clock
Real bugs hide in the gap between empty tables and realistic ones, so seed enough to matter: a few thousand rows spread across a handful of partitions for Cassandra, enough documents for a query planner to make a choice, plus a couple of deliberately awkward values — very long strings, missing optional fields, unicode names — because those are exactly what breaks later.
Keep the fixtures synthetic. Names, addresses, and account numbers should be generated rather than copied from a customer table, and Australian teams should be comfortable with that position under the Privacy Act and the Australian Privacy Principles: de-identified test data keeps the compliance conversation short. Give any random generator a fixed seed so a failing scenario reproduces identically on a colleague's machine in Brisbane as in your own.
Time is the other half of realism. Expiry windows, audit timestamps, and scheduled rollups all depend on a clock the test does not control, and in Australia the edges are sharper than most European teams expect: New South Wales, Victoria, South Australia, and Tasmania shift their clocks on the first Sunday in October and the first Sunday in April, while Queensland and Western Australia do not. A fixture built around "now" can behave differently depending on where the runner sits. Deterministic clocks matter as soon as a test asserts on expiry windows or audit timestamps, and mocking date and time in Java tests is a pattern worth copying across both databases.
Practices that keep these suites trustworthy
On a build server the container has to be able to run at all, which means Docker on the runner or a Docker-in-Docker service, and it means the image pull happens inside your build budget. Engineers in Perth or Darwin pulling a Cassandra image over regional broadband feel that cost personally; a warm cache or a pre-pulled image on the runner removes it.
A short working agreement keeps the suite both honest and quick, and it costs nothing to write down:
- Pin image tags such as
cassandra:4.1andmongodb:7.0, and record digests, so an upstream release cannot change the behaviour of a green build. - Start one container per test class and reset data between test methods instead of sharing a container across the whole module.
- Create keyspaces, tables, and indexes idempotently in setup code, with
IF NOT EXISTSand named index creation, so reruns behave identically. - Generate fixtures from a fixed seed and synthetic identities, keeping the volume large enough to exercise real query plans without inflating build times.
- Inject a
Clockinto the code under test rather than callingInstant.now()directly, so time-dependent behaviour is reproducible in any time zone. - Give Cassandra a bounded heap — around a gigabyte is usually enough for a test dataset — and set container memory limits so a parallel suite cannot exhaust a small runner.
- Keep container-backed tests in a separate Maven profile executed by the integration-test phase, so the fast unit-test loop stays fast.
What to carry away from this setup
The lasting point is not that Testcontainers is convenient, though it is. It is that integration tests become trustworthy when the database is part of the test fixture rather than an environment you hope someone else prepared: a real Cassandra node, a real MongoDB replica set, realistic and synthetic data, and a clock the test owns.
MongoDB behaves predictably in a container once you accept the extra replica-set step for transactions, and its document model makes fixtures easy to write. Cassandra asks more of you — partition and clustering keys decide whether your queries even work, eventual consistency means assertions need care — and it gives back an honest picture of how your access patterns will behave in production. Teams that accept that, and that data seeding and time control are design decisions rather than afterthoughts, end up with integration tests they can run on a laptop in a Brisbane co-working space and on a self-hosted runner with the same result.