### Basic Auto-Configuration Test Setup Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Annotate your Spring Boot integration test class to enable auto-configuration. The embedded server starts automatically, and `MongoTemplate` is injected pointing to it. `@DirtiesContext` ensures proper cleanup between tests. ```java // Minimal Spring Boot integration test — no extra configuration needed @AutoConfigureDataMongo @SpringBootTest @EnableAutoConfiguration @DirtiesContext public class AutoConfigTest { @Test void mongoTemplateIsAvailable(@Autowired MongoTemplate mongoTemplate) { // The embedded mongod is already running; MongoTemplate connects to it automatically assertThat(mongoTemplate.getDb()).isNotNull(); assertThat(mongoTemplate.getDb().getName()).isNotEmpty(); } } ``` -------------------------------- ### JSON Import Configuration Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md Configure a bean for `MongoImportArguments` to start a mongoimport process when MongoDB is running. If `mongoimport` is not bundled, define a tools version. ```java ${importJsonClass} ``` -------------------------------- ### Customize Mongod Process Output Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Use TypedBeanPostProcessor to apply a transformation function to beans of a specific type before initialization. This example redirects Mongod process output to a named console. ```java // Customize the Mongod process configuration bean — redirect output to a named console @Configuration public class LocalConfig { @Bean BeanPostProcessor customizeMongod() { // Only intercepts Mongod beans; all other beans pass through unchanged return TypedBeanPostProcessor.applyBeforeInitialization(Mongod.class, src -> Mongod.builder() .from(src) // copy all existing settings .processOutput(Start.to(ProcessOutput.class) .initializedWith(ProcessOutput.namedConsole("custom"))) .build() ); } } ``` -------------------------------- ### Customize MongoClientSettings with Custom Codec Registry Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Register a MongoClientSettingsBuilderCustomizer bean to adjust driver-level settings. This example maps BSON DATE_TIME to Java LocalDateTime. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer; import com.mongodb.MongoClientSettings; import org.bson.codecs.configuration.CodecRegistries; import org.bson.codecs.pojo.PojoCodecProvider; import org.bson.types.BsonType; import java.util.HashMap; import java.util.Map; import java.time.LocalDateTime; import org.bson.codec.configuration.CodecRegistries; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.bson.types.BsonType; @Configuration public class MongoClientSettingsConfig { @Bean public MongoClientSettingsBuilderCustomizer mongoClientSettingsBuilderCustomizer() { // Map BSON DATE_TIME to Java LocalDateTime Map> replacements = new HashMap<>(); replacements.put(BsonType.DATE_TIME, LocalDateTime.class); BsonTypeClassMap classMap = new BsonTypeClassMap(replacements); return builder -> builder.codecRegistry(CodecRegistries.fromRegistries( CodecRegistries.fromProviders(new DocumentCodecProvider(classMap)), MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()) )); } } ``` ```java import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.EnableAutoConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.context.annotation.Import; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import com.mongodb.BasicDBObject; import org.bson.Document; import java.time.LocalDateTime; import java.time.Month; import static org.assertj.core.api.Assertions.assertThat; // Test verifying custom codec is in effect @AutoConfigureDataMongo @SpringBootTest @EnableAutoConfiguration @DirtiesContext @Import(MongoClientSettingsConfig.class) public class CustomizeMongoClientSettingsTest { @Test void localDateTimeRoundTrips(@Autowired MongoTemplate mongoTemplate) { LocalDateTime dateTime = LocalDateTime.of(2027, Month.AUGUST, 3, 12, 0, 5); mongoTemplate.getDb().getCollection("sample") .insertOne(new Document("name", "klaus").append("meetMe", dateTime)); Document first = mongoTemplate.getDb().getCollection("sample").find().first(); assertThat(first).isNotNull(); assertThat(first.get("meetMe")).isEqualTo(dateTime); // decoded as LocalDateTime } } ``` -------------------------------- ### Adjust Embedded MongoDB Start Timeout Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Increase the default startup timeout for embedded MongoDB by setting the 'de.flapdoodle.mongodb.embedded.starttimeout' property. This is useful for slower environments or larger binaries. ```java import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.annotation.DirtiesContext; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.mongo.data.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import static org.assertj.core.api.Assertions.assertThat; @AutoConfigureDataMongo @SpringBootTest( properties = { "de.flapdoodle.mongodb.embedded.starttimeout=10000" // 10 seconds } ) @EnableAutoConfiguration @DirtiesContext public class CustomStartTimeoutTest { @Test void startsWithinTimeout(@Autowired MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); } } ``` -------------------------------- ### Test Isolation with @TestPropertySource Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md Achieve test isolation by annotating your test class with `@TestPropertySource` to ensure each test gets its own MongoDB instance. ```java ${firstIsolation} ``` -------------------------------- ### Enable Transactions with Spring Data Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md To enable transactions with Spring Data, configure a MongoTransactionManager bean. This setup is useful when you need to ensure atomicity for multiple database operations within a service. ```java public interface PersonRepository extends MongoRepository { } ``` ```java @Service public class PersonService { private PersonRepository repository; @Autowired public PersonService(PersonRepository repository) { this.repository = repository; } @Transactional public void insert(String ... names) { for (String name : names) { repository.insert(new Person(name.substring(0, 1), name)); } } public long count() { return repository.count(); } } ``` ```java @Configuration public class TransactionalConfig { @Bean MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory dbFactory) { return new MongoTransactionManager(dbFactory); } @Bean MongodArguments mongodArguments() { return MongodArguments.builder() .replication(Storage.of("test", 10)) .build(); } } ``` ```java @AutoConfigureDataMongo @SpringBootTest( properties = "de.flapdoodle.mongodb.embedded.version=5.0.5" ) @EnableAutoConfiguration() @DirtiesContext public class TransactionalTest { @Test void personExample(@Autowired PersonService service) { service.insert("Klaus","Susi"); assertThat(service.count()).isEqualTo(2); assertThatThrownBy(() -> service.insert("Helga","Hans")) .isInstanceOf(RuntimeException.class); assertThat(service.count()).isEqualTo(2); } } ``` -------------------------------- ### Customize MongoClientSettings Configuration Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md Customize `MongoClientSettings` by providing a configuration bean. ```java ${customizeMongoClientSettings.config} ``` ```java ${customizeMongoClientSettings} ``` -------------------------------- ### Configure Replica Set and Transaction Manager Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Configure a replica set by exposing a MongodArguments bean with Storage.of, and register a MongoTransactionManager. The auto-configuration detects replication and disables --nojournal. ```java @Configuration public class TransactionalConfig { @Bean MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory dbFactory) { return new MongoTransactionManager(dbFactory); } @Bean MongodArguments mongodArguments() { return MongodArguments.builder() .replication(Storage.of("testReplSet", 10)) // 10 MB oplog .build(); } } ``` ```java // Service using @Transactional @Service public class PersonService { @Autowired private PersonRepository repository; @Transactional public void insert(String... names) { for (String name : names) { repository.insert(new Person(name.substring(0, 1), name)); // If any insert throws, the whole transaction is rolled back } } public long count() { return repository.count(); } } ``` ```java // Test verifying rollback behaviour @AutoConfigureDataMongo @SpringBootTest(properties = "de.flapdoodle.mongodb.embedded.version=5.0.5") @EnableAutoConfiguration @DirtiesContext public class TransactionalTest { @Test void transactionRollsBackOnError(@Autowired PersonService service) { service.insert("Klaus", "Susi"); assertThat(service.count()).isEqualTo(2); // This call throws midway through → entire transaction is rolled back assertThatThrownBy(() -> service.insert("Helga", "Hans")) .isInstanceOf(RuntimeException.class); // Count unchanged: rollback worked assertThat(service.count()).isEqualTo(2); } } ``` -------------------------------- ### Customize Mongod Configuration Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md Further customize the mongod configuration by implementing a `BeanPostProcessor` or using `TypedBeanPostProcessor`. ```java ${customizeMongod.config} ``` ```java ${customizeMongod} ``` -------------------------------- ### Customize Mongod Bean Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Customize the Mongod instance before it is initialized by using a TypedBeanPostProcessor. This allows for fine-grained control over the MongoDB process startup, such as modifying its output. ```java @Configuration public class LocalConfig { @Bean BeanPostProcessor customizeMongod() { return TypedBeanPostProcessor.applyBeforeInitialization(Mongod.class, src -> { return Mongod.builder() .from(src) .processOutput(Start.to(ProcessOutput.class) .initializedWith(ProcessOutput.namedConsole("custom"))) .build(); }); } } ``` ```java @AutoConfigureDataMongo @SpringBootTest() @EnableAutoConfiguration @DirtiesContext public class CustomizeMongodTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); } } ``` -------------------------------- ### TypedBeanPostProcessor Full Constructor Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Use the full constructor form of TypedBeanPostProcessor to supply both before- and after-initialization transformation functions for a specific bean type. ```java BeanPostProcessor processor = new TypedBeanPostProcessor<>( MongodArguments.class, before -> MongodArguments.builder().from(before).useNoJournal(false).build(), Function.identity() // no-op after initialization ); ``` -------------------------------- ### Import JSON Data into MongoDB Collections Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Pre-populate collections before tests by providing a `List` bean. The auto-configuration runs `mongoimport` after the `mongod` process is ready. Ensure `tools-version` is set in `application.properties` if `mongoimport` is not bundled with the selected MongoDB version. ```java @AutoConfigureDataMongo @SpringBootTest @EnableAutoConfiguration @DirtiesContext @Import(ImportJsonTest.Config.class) public class ImportJsonTest { @Test void collectionsArePrePopulated(@Autowired MongoTemplate mongoTemplate) { // "first" collection was loaded from first.json List first = mongoTemplate.getDb() .getCollection("first") .find() .into(new ArrayList<>()); assertThat(first).hasSize(3) .anyMatch(doc -> "Cassandra".equals(doc.get("name", String.class))); // "second" collection was loaded from second.json List second = mongoTemplate.getDb() .getCollection("second") .find() .into(new ArrayList<>()); assertThat(second).hasSize(2) .anyMatch(doc -> "Susi".equals(doc.get("name", String.class))); } static class Config { @Bean public List jsonImportArguments() { return Arrays.asList( MongoImportArguments.builder() .databaseName("test") .collectionName("first") .importFile(ImportJsonTest.class.getResource("/first.json").getFile()) .isJsonArray(true) .upsertDocuments(true) .build(), MongoImportArguments.builder() .databaseName("test") .collectionName("second") .importFile(ImportJsonTest.class.getResource("/second.json").getFile()) .isJsonArray(true) .upsertDocuments(true) .build() ); } } } ``` -------------------------------- ### Custom Database Directory Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md Specify a custom directory for the MongoDB data files. ```java ${customDatabaseDir} ``` -------------------------------- ### Configure Embedded MongoDB Properties Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Use these properties to configure the embedded MongoDB version, tools version, database directory, startup timeout, and replica set settings. ```properties # Required: MongoDB version to download and run de.flapdoodle.mongodb.embedded.version=4.4.0 # Optional: separate mongo-tools version when mongoimport is not bundled de.flapdoodle.mongodb.embedded.tools-version=100.8.0 # Optional: persist data across test runs in a fixed directory de.flapdoodle.mongodb.embedded.databaseDir=${java.io.tmpdir}/myapp-mongo-test # Optional: override startup timeout in milliseconds (default: auto) de.flapdoodle.mongodb.embedded.starttimeout=30000 # Optional: replica set configuration for transaction support de.flapdoodle.mongodb.embedded.storage.replSetName=testReplSet de.flapdoodle.mongodb.embedded.storage.oplogSize=10MB ``` -------------------------------- ### Enable Transactions with Spring Data Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md To enable transactions with Spring Data, set up a minimal configuration including a repository, service, and `MongoTransactionManager`. ```java ${transaction.repository} ``` ```java ${transaction.service} ``` ```java ${transaction.config} ``` -------------------------------- ### Customize MongoClientSettings Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Customize MongoClientSettings by providing a MongoClientSettingsBuilderCustomizer bean. This is useful for configuring codec registries, such as mapping BSON types to specific Java classes like LocalDateTime. ```java @Configuration public class MongoClientSettingsConfig { @Bean public MongoClientSettingsBuilderCustomizer mongoClientSettingsBuilderCustomizer() { Map> replacements = new HashMap<>(); replacements.put(BsonType.DATE_TIME, LocalDateTime.class); BsonTypeClassMap classMap = new BsonTypeClassMap(replacements); return builder -> builder.codecRegistry(CodecRegistries.fromRegistries( CodecRegistries.fromProviders(new DocumentCodecProvider(classMap)), MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()) )); } } ``` ```java @AutoConfigureDataMongo @SpringBootTest() @EnableAutoConfiguration @DirtiesContext public class CustomizeMongoClientSettingsTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { LocalDateTime dateTime = LocalDateTime.of(2027, Month.AUGUST, 3, 12, 0, 5); mongoTemplate.getDb().getCollection("sample") .insertOne( new Document("name", "klaus") .append("meetMe", dateTime) ); Document first = mongoTemplate.getDb().getCollection("sample").find().first(); assertThat(first).isNotNull(); assertThat(first.get("meetMe")).isEqualTo(dateTime); } } ``` -------------------------------- ### Customize Database Directory Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Configure a custom directory for the MongoDB database files by setting the 'de.flapdoodle.mongodb.embedded.databaseDir' property. This is useful for managing where temporary database files are stored. ```java @AutoConfigureDataMongo @SpringBootTest( properties = { "de.flapdoodle.mongodb.embedded.databaseDir=${java.io.tmpdir}/customDir/${random.uuid}" } ) @EnableAutoConfiguration @DirtiesContext public class CustomDatabaseDirTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { Assertions.assertThat(mongoTemplate.getDb()).isNotNull(); } } ``` -------------------------------- ### Enable MongoDB Authentication with Spring Boot Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Enable MongoDB authentication by setting `spring.mongodb.username` and `spring.mongodb.password` properties. The auto-configuration enables `--auth` on `mongod` and creates the user in the target database before any client connects. ```java @AutoConfigureDataMongo @SpringBootTest( properties = { "de.flapdoodle.mongodb.embedded.version=4.4.18", "spring.mongodb.username=customUser", "spring.mongodb.password=userPassword123" } ) @EnableAutoConfiguration @DirtiesContext public class AuthTest { @Test void authenticatedClientWorks(@Autowired MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); mongoTemplate.getDb().getCollection("first").insertOne(new Document("value", "a")); mongoTemplate.getDb().getCollection("second").insertOne(new Document("value", "b")); Document result = mongoTemplate.getDb().runCommand(new Document("listCollections", 1)); assertThat(result).containsEntry("ok", 1.0); // Both collections are visible to the authenticated user assertThat(result) .extracting(doc -> doc.get("cursor"), as(MAP)) .containsKey("firstBatch") .extracting(cursor -> cursor.get("firstBatch"), as(LIST)) .hasSize(2); } } ``` -------------------------------- ### Import JSON Data into MongoDB Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Import JSON data into MongoDB collections before test execution by defining a bean for `List`. Specify database, collection, import file, and other options. ```java @AutoConfigureDataMongo @SpringBootTest() @EnableAutoConfiguration() @DirtiesContext @Import(ImportJsonTest.Config.class) public class ImportJsonTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); ArrayList first = mongoTemplate.getDb() .getCollection("first") .find() .into(new ArrayList<>()); assertThat(first).hasSize(3) .anyMatch(doc -> doc.get("name", String.class).equals("Cassandra")); ArrayList second = mongoTemplate.getDb() .getCollection("second") .find() .into(new ArrayList<>()); assertThat(second).hasSize(2) .anyMatch(doc -> doc.get("name", String.class).equals("Susi")); } static class Config { @Bean public List jsonImportArguments() { return Arrays.asList(MongoImportArguments.builder() .databaseName("test") .collectionName("first") .importFile(ImportJsonTest.class.getResource("/first.json").getFile()) .isJsonArray(true) .upsertDocuments(true) .build(), MongoImportArguments.builder() .databaseName("test") .collectionName("second") .importFile(ImportJsonTest.class.getResource("/second.json").getFile()) .isJsonArray(true) .upsertDocuments(true) .build()); } } } ``` -------------------------------- ### Test Isolation with @DirtiesContext Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md For test isolation with the same configuration, use `@DirtiesContext` to ensure each test has its own dedicated MongoDB instance. ```java ${secondIsolation} ``` -------------------------------- ### Persist Embedded MongoDB Data with Custom Database Directory Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Configure a custom directory for embedded MongoDB data by setting the 'de.flapdoodle.mongodb.embedded.databaseDir' property. This allows data persistence across restarts. Use Spring property placeholders for dynamic paths. ```java import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.annotation.DirtiesContext; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.mongo.data.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import static org.assertj.core.api.Assertions.assertThat; @AutoConfigureDataMongo @SpringBootTest( properties = { // Each test run gets a unique subdirectory via ${random.uuid} "de.flapdoodle.mongodb.embedded.databaseDir=${java.io.tmpdir}/customDir/${random.uuid}" } ) @EnableAutoConfiguration @DirtiesContext public class CustomDatabaseDirTest { @Test void usesCustomDir(@Autowired MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); // Data is written to the custom directory, not a temp location } } ``` -------------------------------- ### Transaction Test Case Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md This test case demonstrates transaction behavior where some calls succeed and others fail, preventing the transaction from being committed. ```java ${transaction.test} ``` -------------------------------- ### Test Isolation with `@DirtiesContext` Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Ensure test isolation even with the same configuration by annotating the test class with `@DirtiesContext`. This forces a new MongoDB instance for each test. ```java @AutoConfigureDataMongo @SpringBootTest() @EnableAutoConfiguration @DirtiesContext @TestPropertySource(properties = "property=A") public class AutoConfigSecondIsolationTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { mongoTemplate.getDb().createCollection("deleteMe"); long count = mongoTemplate.getDb().getCollection("deleteMe").countDocuments(Document.parse("{}")); assertThat(mongoTemplate.getDb()).isNotNull(); assertThat(count).isEqualTo(0L); } } ``` -------------------------------- ### Isolate Embedded MongoDB Instances with @TestPropertySource Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Use @TestPropertySource with unique property values to create separate embedded MongoDB instances for different test groups. @DirtiesContext ensures a fresh context and instance after each test class. ```java import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.TestPropertySource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.mongo.data.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.junit.jupiter.api.Test; import com.mongodb.Document; import static org.assertj.core.api.Assertions.assertThat; // Test group A — gets its own embedded instance because of the unique property value @AutoConfigureDataMongo @SpringBootTest @EnableAutoConfiguration @DirtiesContext @TestPropertySource(properties = "property=A") public class AutoConfigFirstIsolationTest { @Test void isolatedInstance(@Autowired MongoTemplate mongoTemplate) { // This collection is created only in this instance mongoTemplate.getDb().createCollection("deleteMe"); long count = mongoTemplate.getDb() .getCollection("deleteMe") .countDocuments(Document.parse("{}")); assertThat(count).isEqualTo(0L); } } // Test group B — same property value as A → shares the same context/instance // but @DirtiesContext forces teardown after this class @AutoConfigureDataMongo @SpringBootTest @EnableAutoConfiguration @DirtiesContext @TestPropertySource(properties = "property=A") public class AutoConfigSecondIsolationTest { @Test void sharedContextButFreshAfterwards(@Autowired MongoTemplate mongoTemplate) { mongoTemplate.getDb().createCollection("deleteMe"); long count = mongoTemplate.getDb() .getCollection("deleteMe") .countDocuments(Document.parse("{}")); assertThat(count).isEqualTo(0L); } } ``` -------------------------------- ### Specify MongoDB Version at Test Level Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Override the default MongoDB version for a specific test class using `@TestPropertySource`. This allows testing against different MongoDB versions within the same project. The `spring.mongodb.uri` can also be specified, though host/port are injected automatically. ```java @AutoConfigureDataMongo @SpringBootTest @EnableAutoConfiguration @DirtiesContext @TestPropertySource(properties = { "de.flapdoodle.mongodb.embedded.version=6.0.3", "spring.mongodb.uri=mongodb://localhost/test" // host/port are injected automatically }) public class SpecifyMongoConnectionWithNewerVersionTest { @Test void connectsToSpecifiedVersion(@Autowired MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); ArrayList collections = mongoTemplate.getDb() .listCollectionNames() .into(new ArrayList<>()); assertThat(collections).isEmpty(); } } ``` -------------------------------- ### Add Maven Dependency for Embedded MongoDB Spring Integration Source: https://context7.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/llms.txt Include this dependency in your project's test classpath. An SLF4J adapter is also required for logging. ```xml de.flapdoodle.embed de.flapdoodle.embed.mongo.spring4x 4.24.0 test org.slf4j slf4j-simple 2.0.9 test ``` -------------------------------- ### Add Maven Dependency for Spring 4.x.x Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/README.md Include this dependency in your Maven project to use the Embedded MongoDB Spring integration for Spring 4.x.x versions. Ensure you have a compatible SLF4J API version (e.g., 2.0.xx) for logging. ```xml de.flapdoodle.embed de.flapdoodle.embed.mongo.spring4x 4.24.0 ``` -------------------------------- ### Test Isolation with `@TestPropertySource` Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Achieve test isolation by annotating your test class with `@TestPropertySource`. This ensures each test runs with its own MongoDB instance, preventing interference between tests. ```java @AutoConfigureDataMongo @SpringBootTest() @EnableAutoConfiguration @DirtiesContext @TestPropertySource(properties = "property=A") public class AutoConfigFirstIsolationTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { mongoTemplate.getDb().createCollection("deleteMe"); long count = mongoTemplate.getDb().getCollection("deleteMe").countDocuments(Document.parse("{}")); assertThat(mongoTemplate.getDb()).isNotNull(); assertThat(count).isEqualTo(0L); } } ``` -------------------------------- ### Exclude EmbeddedMongoAutoConfiguration Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md To test with an unmanaged MongoDB database, disable the auto-configuration by excluding `EmbeddedMongoAutoConfiguration`. ```java @EnableAutoConfiguration(exclude = {EmbeddedMongoAutoConfiguration.class}) ``` -------------------------------- ### Disable Spring Autoconfiguration Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/src/test/resources/de/flapdoodle/embed/mongo/spring/autoconfigure/HowTo.md To prevent Spring from automatically configuring the embedded MongoDB, disable the autoconfiguration class. ```java ${autoConfigClass} ``` -------------------------------- ### Disable Spring Data MongoDB Autoconfiguration Source: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring/blob/main/HowTo.md Disable the default Spring Data MongoDB autoconfiguration by excluding the relevant class. This is necessary when using the embeddable MongoDB integration. ```java @AutoConfigureDataMongo @SpringBootTest() @EnableAutoConfiguration @DirtiesContext public class AutoConfigTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { Assertions.assertThat(mongoTemplate.getDb()).isNotNull(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.