How to make the junit tests use the embedded mongoDB in a springboot application? How to make the junit tests use the embedded mongoDB in a springboot application? mongodb mongodb

How to make the junit tests use the embedded mongoDB in a springboot application?


An alternative would be to run entire spring boot application in test. In this case your spring boot application will be discovered automatically and embedded mongoDB will be downloaded and started by Spring Boot

@RunWith(SpringRunner.class)@SpringBootTestpublic class YourSpringBootApplicationTests {

08:12:14.676 INFO EmbeddedMongo:42 - note: noprealloc may hurt performance in many applications 08:12:14.694 INFO EmbeddedMongo:42 - 2017-12-31T08:12:14.693+0200 I CONTROL [initandlisten] MongoDB starting : pid=2246 port=52299 08:12:22.005 INFO connection:71 - Opened connection [connectionId{localValue:2, serverValue:2}] to localhost:52299

In case of your example you might modify the code in order to start embedded Mongo on different port:

  1. add test/resoures/test.properties file in order to override properties from application.properties

    mongo.db.name=person_testDBmongo.db.url=localhostmongo.db.port=12345
  2. modify MongoDBConfig: add MONGO_DB_PORT field

    @EnableMongoRepositoriespublic class MongoDBConfig {    @Value("${mongo.db.url}")    private String MONGO_DB_URL;    @Value(("${mongo.db.port:27017}"))    private int MONGO_DB_PORT;    @Value("${mongo.db.name}")    private String MONGO_DB_NAME;    @Bean    public MongoTemplate mongoTemplate() {        MongoClient mongoClient = new MongoClient(MONGO_DB_URL, MONGO_DB_PORT);        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME);        return mongoTemplate;    }}
  3. modify test class:remove @DataMongoTest annotation. This annotation forces starting embedded mongoDB instance

    static MongodExecutable mongodExecutable;@BeforeClasspublic static void setup() throws Exception {    MongodStarter starter = MongodStarter.getDefaultInstance();    String bindIp = "localhost";    int port = 12345;    IMongodConfig mongodConfig = new MongodConfigBuilder()            .version(Version.Main.PRODUCTION)            .net(new Net(bindIp, port, Network.localhostIsIPv6()))            .build();    mongodExecutable = null;    try {        mongodExecutable = starter.prepare(mongodConfig);        mongodExecutable.start();    } catch (Exception e){        // log exception here        if (mongodExecutable != null)            mongodExecutable.stop();    }}@AfterClasspublic static void teardown() throws Exception {    if (mongodExecutable != null)        mongodExecutable.stop();}

One more way is to use MongoRepository and init embedded Mongo as part of test @Configuration class: it's outlined here: How do you configure Embedded MongDB for integration testing in a Spring Boot application?