Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo
The available alternatives of the @Sql Spring Data annotation for MongoDB in Java. Jamolingo as the closest solution for the @Sql experience.
Integration testing is the backbone of reliable data-driven Java applications. When working with relational databases in the Spring ecosystem, setting up test data per test method is effortless thanks to the org.springframework.test.context.jdbc.Sql annotation.
However, once you move to MongoDB, you quickly notice a gap. Spinning up a real MongoDB instance for tests is easier than ever — whether you use Testcontainers with the official MongoDB Java Driver or Embedded MongoDB in Spring Boot — but Spring Data MongoDB does not provide a built-in equivalent to the @Sql annotation for declaratively seeding collections, cleaning up data, or managing indexes before each test.
In this article, we will look at why @Sql is so productive for relational databases, compare four practical approaches for seeding and managing MongoDB state in Java integration tests, using Flyway or Liquibase libraries, and also explore how the junit5-mongo-extension library brings a true @Sql-like experience.
The Gold Standard in Relational Testing: Spring's @Sql Annotation
In Spring integration tests backed by SQL databases, the Sql annotation lets you declaratively execute SQL scripts before or after a test class or test method:
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
class UserSqlRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
@Sql(scripts = {"/sql/clear_users.sql", "/sql/insert_active_users.sql"},
executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
void shouldFindActiveUsers() {
List<User> activeUsers = userRepository.findByActiveTrue();
assertThat(activeUsers).hasSize(3);
}
}
What makes the Sql annotation so developer-friendly?
- Declarative and self-documenting: Looking at the test method immediately tells you what data preconditions apply.
- Per-test isolation: Different test methods in the same class can load completely different datasets or schema tweaks.
- Zero boilerplate: No manual file reading, JSON/SQL parsing, or lifecycle hook plumbing in your test classes.
Current Testing Solutions for MongoDB
When working with MongoDB and testing complex aggregation pipelines or full-text search, we need the same level of control over documents and MongoDB Atlas indexes.
Yet out of the box, there is no @MongoSql or @MongoData annotation in Spring.
Available Alternatives for Testing Integration With MongoDB in Java
Although there is no annotation implemented yet that makes testing really user-friendly in Spring for MongoDB, there are a couple of approaches that could be used as alternatives to fill this gap.
Option A: Programmatic Seeding With MongoTemplate and Jackson (@BeforeEach)
The most common approach in Spring Boot applications is reading JSON files from the classpath and inserting them programmatically inside JUnit 5's @BeforeEach lifecycle method using MongoTemplate and Jackson's ObjectMapper.
@DataMongoTest
class UserRepositoryTest {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private ObjectMapper objectMapper;
@BeforeEach
void setUp() throws Exception {
// Clear collection
mongoTemplate.dropCollection(User.class);
// Load JSON dataset from test resources
List<User> users = objectMapper.readValue(
new ClassPathResource("data/users.json").getInputStream(),
new TypeReference<List<User>>() {}
);
// Insert into MongoDB
mongoTemplate.insert(users, User.class);
}
@Test
void testFindUser() {
// Test logic here...
}
}
Pros:
- No extra libraries required beyond Spring Boot starter dependencies.
- Full programmatic flexibility in Java.
Cons:
- Repetitive boilerplate: Every test class needs resource loading and cleanup code.
- Poor per-method granularity:
@BeforeEachruns the same setup for every test in the class. If different tests require different JSON files or index configurations, you end up calling helper methods inside every@Testmethod. - Type coupling: Using Jackson, the ObjectMapper ties the JSON format to your Java entity mapping rather than MongoDB Extended JSON/raw BSON types (such as
ObjectId,ISODate, orDecimal128).
Option B: Custom Annotation + Spring TestExecutionListener
If you want a declarative syntax similar to the @Sql (for example, @MongoDataSet("/data/users.json")), you can build a custom annotation paired with a Spring TestExecutionListener.
First, define the Annotation.
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MongoDataSet {
String[] value(); // Paths to JSON files on the classpath
String collection();
}
Then implement the TestExecutionListener.
public class MongoDataSetTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
MongoDataSet annotation = AnnotatedElementUtils.findMergedAnnotation(
testContext.getTestMethod(), MongoDataSet.class);
if (annotation == null) {
annotation = AnnotatedElementUtils.findMergedAnnotation(
testContext.getTestClass(), MongoDataSet.class);
}
if (annotation != null) {
MongoTemplate mongoTemplate = testContext.getApplicationContext()
.getBean(MongoTemplate.class);
mongoTemplate.dropCollection(annotation.collection());
for (String path : annotation.value()) {
String json = StreamUtils.copyToString(
new ClassPathResource(path).getInputStream(), StandardCharsets.UTF_8);
Document doc = Document.parse(json);
mongoTemplate.insert(doc, annotation.collection());
}
}
}
}
Pros:
- Declarative and tailored to your exact project needs.
- Keeps test classes clean.
Cons:
- You own the maintenance: As soon as you need JSON arrays vs. single documents, multiple collections per test, write concerns, batch inserts, standard index creation, or Atlas Search index readiness checks, your "simple" listener grows into a custom framework that you have to test and maintain yourself.
Option C: Testcontainers + Migration Tools (Flyway/Liquibase)
When your integration tests spin up ephemeral databases using Testcontainers (or Quarkus DevServices), another common enterprise pattern is combining containers with database migration tools such as Liquibase (via the Liquibase MongoDB extension) or Flyway (which supports MongoDB migrations in recent versions):
With this approach, you have to follow these steps:
- Spin up a
MongoDBContainer(Embedded is also a good alternative) orMongoDBAtlasLocalContainer. - Let Liquibase or Flyway automatically execute migration scripts on startup to create collections, validation rules, and baseline indexes.
- Use a JUnit 5 callback or utility helper to clean or seed collections between tests if strict isolation is required.
Pros:
- Production parity: Verifies that your production migration scripts and baseline indexes work against a real MongoDB instance.
Cons:
- Not designed for per-test variations: Migration tools are forward-only and version-controlled for application startup, not for switching datasets or testing different index combinations on a method-by-method basis.
Option D: Declarative Setup With junit5-mongo-extension Library
If you are looking for the closest equivalent to Spring's @Sql for MongoDB—without writing and maintaining custom plumbing, the junit5-mongo-extension sublibrary from the Jamolingo project is purpose-built for this scenario.
Originally created to support extensive integration for Jamolingo (check an OData-to-MongoDB query translator), the junit5-mongo-extension is a lightweight, standalone JUnit 5 extension family with three modules:
- junit5-mongo-extension – Environment-agnostic core (works with any Java framework by extending
AbstractMongoDataLoaderExtension). - junit5-mongo-extension-spring – Ready-to-use Spring/Spring Boot extension (
SpringMongoDataLoaderExtension) that automatically resolvesMongoClientfrom the SpringApplicationContext. - junit5-mongo-extension-quarkus – Ready-to-use Quarkus extension (
QuarkusMongoDataLoaderExtension) that resolvesMongoClientfrom the QuarkusArccontainer.
To use the jamolingo extension, you have to:
Add the dependency (Spring Boot example with Maven as a build tool).
<dependency>
<groupId>com.github.starnowski.jamolingo</groupId>
<artifactId>junit5-mongo-extension-spring</artifactId>
<version>0.10.0</version>
<scope>test</scope>
</dependency>
1. Inserting Documents and Clearing Collections
Using the @MongoSetup and @MongoDocument, you can specify which collections to populate before a test class or test method runs. Each bsonFilePath can point to either a single BSON/JSON document ({...}) or a JSON array of documents ([{...}, {...}]), supporting full MongoDB Extended JSON syntax.
import com.github.starnowski.jamolingo.junit5.MongoDocument;
import com.github.starnowski.jamolingo.junit5.MongoSetup;
import com.github.starnowski.jamolingo.junit5.SpringMongoDataLoaderExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@ExtendWith(SpringMongoDataLoaderExtension.class)
class OrderIntegrationTest {
@Test
@MongoSetup(
batchInsertToCollection = true,
mongoDocuments = {
// Inserts an array or single document from classpath; clears "users" first
@MongoDocument(
database = "shop_db",
collection = "users",
bsonFilePath = "data/users.json"
),
// Multiple files can be loaded into the same collection
@MongoDocument(
database = "shop_db",
collection = "orders",
bsonFilePath = "data/active_orders.json"
),
@MongoDocument(
database = "shop_db",
collection = "orders",
bsonFilePath = "data/archived_orders.json"
),
// Leaving bsonFilePath empty explicitly erases the "audit_logs" collection!
@MongoDocument(
database = "shop_db",
collection = "audit_logs"
)
}
)
void shouldProcessUserOrdersWithCleanAuditLog() {
// 1. "users", "orders", and "audit_logs" collections were automatically cleared once.
// 2. "users" and "orders" were populated in batch mode (insertMany).
// 3. "audit_logs" is guaranteed to be empty.
}
}
Key behaviors:
- Automatic cleanup: Before inserting documents into a target collection, the extension automatically clears existing documents in that collection (
deleteMany(new Document())). - Explicit collection clearing: If you leave
bsonFilePathempty (the default), the extension simply clears that collection without inserting anything. - Multiple files per collection: If you list multiple
@MongoDocumententries for the same collection, the collection is cleared only once at the beginning of setup, and then all specified files are inserted.
2. Managing and Synchronizing MongoDB Atlas Search Indexes
Testing MongoDB Atlas Search ($search and $searchMeta aggregation stages) locally with the mongodb/mongodb-atlas-local Docker image in Testcontainers introduces a notorious challenge (Atlas Search indexes are built and updated asynchronously in the background).
If you insert documents and immediately run a $search query in your test, the test will randomly fail because the Lucene-based Atlas Search index hasn't finished indexing the newly inserted documents yet.
The junit5-mongo-extension solves this with the @AtlasSearchIndex and the @AtlasSearchIndexValidation:
@SpringBootTest
@ExtendWith(SpringMongoDataLoaderExtension.class)
@AtlasSearchIndexValidation(
maxWaitDuration = 45,
maxWaitUnit = TimeUnit.SECONDS,
pollInterval = 500,
pollIntervalUnit = TimeUnit.MILLISECONDS
)
class AtlasSearchIntegrationTest {
@Test
@MongoSetup(
mongoDocuments = {
@MongoDocument(
database = "test_db",
collection = "items",
bsonFilePath = "data/items.json"
)
},
atlasSearchIndexes = {
@AtlasSearchIndex(
name = "default",
database = "test_db",
collection = "items",
bsonFilePath = "search/items_search_index.json",
validationProperty = {"name", "description"}
)
}
)
void shouldFindItemsUsingAtlasSearch() {
// At this point:
// 1. "items" collection is cleared and populated.
// 2. The "default" Atlas Search index is created (or replaced if its JSON definition changed).
// 3. The extension has waited until the index is READY and all documents' "name" and "description"
// fields are searchable!
}
}
Where search/items_search_index.json defines your Atlas Search mappings and analyzers:
{
"mappings": {
"dynamic": false,
"fields": {
"name": [
{ "type": "string" }
],
"description": [
{ "type": "string" }
]
}
}
}
Behind the scenes, the @AtlasSearchIndex handles the entire lifecycle:
- Creation, modification, and caching: It checks whether the target search index already exists and matches the cached JSON definition. If the index doesn't exist, it creates it. If a test uses a different
bsonFilePath(modifying the index definition), the extension drops the old search index, waits until it is removed, and creates the new one. - Multi-stage synchronization validation: After inserting documents, it runs a pipeline of validation strategies (customizable via
validationStrategies):- AtlasSearchIndexReadinessSyncValidationStrategy – Polls until the Atlas Search index status reaches
"READY". - AtlasSearchIndexDocumentCountSyncValidationStrategy – Polls
$searchMetauntil the indexed document count for eachvalidationPropertymatches the actual collection document count. - AtlasSearchIndexValuesSyncValidationStrategy – Executes
$searchqueries for the actual values ofvalidationPropertyin your inserted documents until the expected document_ids are returned.
- AtlasSearchIndexReadinessSyncValidationStrategy – Polls until the Atlas Search index status reaches
Practical Recommendations: Which One Should You Choose?
1. Programmatic Seeding (@BeforeEach) or a Custom Implementation (Options A–B)
- Choose Option A if you have a small microservice with only a handful of simple repository tests, where every test shares the exact same dataset, and you want zero extra test dependencies.
- Choose Option B only if your organization has strict policies against third-party test libraries or requires tightly coupled custom logic (such as encrypting fields via an internal KMS during test data loading).
2. Flyway or Liquibase (Option C)
- Use Liquibase or Flyway alongside Testcontainers to apply your application-wide baseline migrations (creating collections, JSON schema validators, production indexes, and static dictionary data) when the test container starts up.
- Think of Flyway/Liquibase as the MongoDB equivalent of running your production DDL migrations before the test suite starts — not as a replacement for per-test data seeding.
3. Jamolingo's junit5-mongo-extension (Option D)
- Choose
junit5-mongo-extensionwhenever you want the productivity of Spring's @Sql in MongoDB integration tests. - It is the ideal choice when different test methods need different document sets, when you need to declaratively clear collections, when you test index-sensitive queries, or when you test MongoDB Atlas Search and need deterministic index synchronization without flaky tests.
- Best of all, you can combine Option C and Option E: let Liquibase/Flyway verify your baseline migrations on container startup, and use
@MongoSetupon your test methods to seed test-specific documents and indexes!
Opinions expressed by DZone contributors are their own.