Can I test my Repository in Spring Boot without actually saving test data in the database?

Viewed 806

I have a Spring Boot application with some REST endpoints and I have a MongoDB. I would like to create a test that runs every time the project is built. The test should simply take some mock data and put it into the database and use that mock data to test that the endpoints return the correct results. If it's possible, I don't want the mock data to actually go all the way to the database. I believe I've seen something before where Spring could simulate the database. Can anyone point me in the right direction?

2 Answers

If you wanna "unit" test your controller You can use @WebMvcTest and just mock your service calls from controller. Find out here a pretty good getting started with @WebMvcTest https://reflectoring.io/spring-boot-web-controller-test/

If you really need to do integration tests You can use embedded mongoDb database and @SpringBootTest in combination with @DataMongoTest annotation (Find out here how to do that. @SpringBootTest will load your applicationContext and @DataMongoTest will autoconfigure all you need for seting up the embedded mongoDb database.

de.flapdoodle.embed.mongo provides embedded MongoDB for integration tests. So you need to add its dependency.

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

If you wanna prefill your database you can create a bean in a spring configuration class

@Bean
  public Boolean preFill(MongoTemplate mongoTemplate) throws IOException {
     JSONParser parser = getJsonParser();
      List dbObjects = /* Init your objects to insert here */;

      for (Object dbObject : dbObjects) {
        Document document = new Document(parser.parseJson(JSON.serialize(dbObject)));
        mongoTemplate.insert(document, dbObject.getKey());
      }
    });
    return true;
  }
  
  private JSONParser getJsonParser() {
    JsonParserFactory factory= JsonParserFactory.getInstance();
    return factory.newJsonParser();
  }
Related