'How to prevent instantiation of original mongo configuration bean in SpringBootTest?

I would like to use embedded MongoDB for my integration tests and have added the flapdoodle dependency in pom.xml.

However, I have the following config class that is used to connect to an actual MongoDB instance:

@Configuration
public class DbConfig extends AbstractMongoClientConfiguration {

  @Value("${spring.data.mongodb.username}")
  private String username;

  @Value("${spring.data.mongodb.password}")
  private String password;

  @Value("${spring.data.mongodb.database}")
  private String database;

  @Value("${spring.data.mongodb.host}")
  private String host;

  @Value("${spring.data.mongodb.port}")
  private String port;


  @Override
  public MongoClient mongoClient() {
    String url = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/" + database;
    MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(new ConnectionString(url).build();
    return MongoClients.create(mongoClientSettings);
  }

}

When I do not provide the spring data mongodb parameters in my tests' application.yml and run the SpringbootTest, NoSuchBeanDefinitionException is thrown. On the other hand, if I do specify the spring data parameters, the tests connect to the real mongodb instance instead.

How can I prevent/override the instantiation of the DbConfig bean so that embedded MongoDb can be used?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source