简体   繁体   中英

How to use Embedded MongoDB in Spring Boot 2.2 integration tests?

I want to use Embedded MongoDB instance instead of connecting to my localhost MongoDB.

In integration tests I use only mockMvc. Annotations on my test class

@Profile("it")
@SpringBootTest
//@DataMongoTest - tried to do with that and can't run app because of missing Security beans.
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
public class ControllerIntegrationTest {
   @Autowired
   private WebApplicationContext context;

   @Autowired
   private MockMvc mockMvc;
...
}

MongoDB config

@Configuration
@EnableMongoRepositories
public class MongodbConfiguration {

   @Value("${mongo.db.url:mongodb://127.0.0.1}")
   private String MONGO_DB_URL;

   @Value(("${mongo.db.port:27017}"))
   private int MONGO_DB_PORT;

   @Value("${mongo.db.name:admin}")
   private String MONGO_DB_NAME;

   @Bean
   public MongoClient mongo() {
      return MongoClients.create(MONGO_DB_URL + ":" + MONGO_DB_PORT);
   }

   @Bean
   public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
      return new SimpleMongoClientDbFactory(mongoClient, MONGO_DB_NAME);
   }

   @Bean
   public WriteConcernResolver writeConcernResolver() {
      return action -> {
         System.out.println("Using Write Concern of MAJORITY");
         return WriteConcern.MAJORITY;
      };
   }

   @Bean
   public MongoCustomConversions customConversions(OffsetDateTimeReadConverter offsetDateTimeReadConverter,
         OffsetDateTimeWriteConverter offsetDateTimeWriteConverter) {
      return new MongoCustomConversions(asList(offsetDateTimeReadConverter, offsetDateTimeWriteConverter));
   }
}

I have "de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.2.0" in my build.gradle file:

    testImplementation "org.springframework.boot:spring-boot-starter-test"
    testImplementation "org.mockito:mockito-core:2.23.4"
    testImplementation "org.assertj:assertj-core:3.16.1"
    integrationTest "de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.2.0"

I was trying to do that as stated in How to make the junit tests use the embedded mongoDB in a springboot application? , however it's from 2018 so it may be outdated.

Whenever I run test it still tries to connect to localhost MongoDB instance instead run embedded.

Given it's an IT I'd suggest you to use MongoDB container to run your test, it will give you more precise insights about your app and can be integrated with a CI/CD pipeline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM