@SpringBootTest how to pre-populate embedded MongoDB?

1k views Asked by At

Doing implementation of a microservice with a few endpoints based on Spring Boot and MongoDB and trying to write integration tests using @SpringBootTest annotation capabilities.

At the moment, I am facing an issue that I need to pre-populate an embedded MongoDB instance that instantiated only during 'test' phrase with some test data.

And I did not find any out-of-the-box option available in Spring Boot for this purpose.

Some people advice to use for test data pre-populating tools like mongobee or mongoprefill or nosql-unit but for me, it seems like overhead or workaround, do not want to introduce any new dependencies even in test scope.

So could you please advice: In the current Spring Boot ecosystem, what is the right way to pre-populate MongoDB for testing purpose, when we are talking about integration (end-to-end) testing with @SpringBootTest?

1

There are 1 answers

0
rieckpil On BEST ANSWER

There are multiple ways to pre-populate data:

  1. Use the JUnit lifecycle methods like @BeforeEach, @BeforeAll to fill in data
  2. You could disable the Spring Boot autoconfiguration for the embedded MongoDB and do it on your own and insert data after creating the connection
  3. You could somehow mirror the @Sql feature we have for testing relational databases and write something similar using the AsbtractTestExectuionListener. For this have a look at the Spring class SqlScriptsTestExecutionListener
  4. Provide a class that implements the CommandLineRunner interface and only activate this bean for your integration test profile with @Profile("integration-test")