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.