Although MongoDB cannot be actually embedded there is a nice tool mimicking the behavior of an actual embedded database. When writing Spring Boot application it is quite easy to replace the connection to a Mongo server with a connection to an embedded server with a simple configuration file.
The following configuration file should do the trick and will enable you to transparently use an embedded Mongo server instead of connecting to an actual one.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class TestMongoConfig { | |
private static final MongodStarter starter = MongodStarter.getDefaultInstance(); | |
@SuppressWarnings("SpringJavaAutowiringInspection") | |
@Autowired | |
private MongoProperties properties; | |
@Autowired(required = false) | |
private MongoClientOptions options; | |
@Bean(destroyMethod = "close") | |
public Mongo mongo() throws IOException { | |
Net net = mongod().getConfig().net(); | |
properties.setHost(net.getServerAddress().getHostName()); | |
properties.setPort(net.getPort()); | |
return properties.createMongoClient(this.options); | |
} | |
@Bean(destroyMethod = "stop") | |
public MongodProcess mongod() throws IOException { | |
return mongodExe().start(); | |
} | |
@Bean(destroyMethod = "stop") | |
public MongodExecutable mongodExe() throws IOException { | |
return starter.prepare(mongodConfig()); | |
} | |
@Bean | |
public IMongodConfig mongodConfig() throws IOException { | |
return new MongodConfigBuilder().version(Version.Main.PRODUCTION).build(); | |
} | |
} |