flapdoodle-oss / de.flapdoodle.embed.mongo.spring

embedded mongo spring integration
Apache License 2.0
30 stars 7 forks source link

Always goes on real database and not on embedded database #55

Closed MarcoKnezevichInsiel closed 3 weeks ago

MarcoKnezevichInsiel commented 3 weeks ago

Hi, I hava a spring boot 3.2.5 project with the dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
...
<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo.spring3x</artifactId>
    <version>4.14.0</version>
    <scope>test</scope>
</dependency>

My configuration class is:

@Configuration
public class MongoDbConfig extends AbstractMongoClientConfiguration {
    @Value("${mongodb.database}")
    String nomeDb;
    @Value("${mongodb.uri}")
    String dbUri;

    @Override
    protected String getDatabaseName() {
        return nomeDb;
    }

    @Override
    public MongoClient mongoClient() {
        ConnectionString connectionString = new ConnectionString(dbUri);
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyConnectionString(connectionString)

                .build();
        return MongoClients.create(mongoClientSettings);
    }

}

and in my application.properties I have:

mongodb.uri=mongodb://<my url string>
mongodb.database=<my database>
de.flapdoodle.mongodb.embedded.version=5.0.5

I'm writing an easy test, foolowing the documentation:

and my test is:

@AutoConfigureDataMongo
@SpringBootTest()
@EnableAutoConfiguration
@DirtiesContext
@ActiveProfiles({"test"})
class MongoDbEmbeddedTest {
    @Test
    void checkDbTest(@Autowired final MongoTemplate mongoTemplate) {
        assertThat(mongoTemplate.getDb()).isNotNull();
    }
}

the MongoTemplate instance points to real database and not to Embedded database.

Where am I doing wrong?

Thanks in advance for the answare.

Have a nice day

michaelmosmann commented 3 weeks ago

@MarcoKnezevichInsiel i guess that if you remove mongodb.uri from your property file the test will use the test mongo db?

I will have a look at this.

MarcoKnezevichInsiel commented 3 weeks ago

I have done some refactory and I have assigned a profile mongodb to MongoDbConfigclass and then I ran the test again without the mongodb profile (so the configuration class is ignored) and now it works corrrectly. Thanks for the tip.