Use Embedded MongoDB when active profile is "test"

Viewed 1192

I have

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

in my pom.xml so my Spring Boot application attempts to connect to MongoDB on localhost when the application is started.

I also have

<dependency>
  <groupId>de.flapdoodle.embed</groupId>
  <artifactId>de.flapdoodle.embed.mongo</artifactId>
  <scope>test</scope>
</dependency>

so when I run unit tests the embedded MongoDb is used.

For the purpose of integration testing, I'd like to also use the embedded MongoDB if the application is started with the "test" active profile.

So effectively, I'd like to remove <scope>test</scope> from the embed dependency and have the the embed version used when the active profile is 'test'.

How can I achieve this?

2 Answers

Most probably the solution you are looking for is adding a profiled exclusion of embedded mongo database. Try to follow below steps:

  1. Assume that default profile is for development purposes so you want to run embedded mongo in it. EmbeddedMongoAutoConfiguration is the class responsible for configuration of embedded mongo database. It is run when embedded mongo class is on classpath so just remove test scope as you pointed out
  2. Create a profile for production, docker or whatever suits you and in this profile make sure you add following entry in yml (or properties file):

    spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration

  3. Please bear in mind that embedded mongo is on your classpath now which might be not desired for production environment, so you might wanna also configure maven to exclude it in some maven profile.

Related