Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Spring configuration to use an embedded MongoDB during tests
@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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment