Issue
I created a spring boot application based on Spring Initializr (gradle flavour).
I also added
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
To use a MongoDB for persistence. I also added a simple integration test that works fine:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TileServiceApplicationTests {
@Autowired
private MockMvc mvc;
@Autowired
private UserSettingRepository userSettingRepository;
@Test
public void contextLoads() throws Exception {
Folder folder = random( Folder.class, "color", "elements" );
EserviceTile eserviceTile1 = random( EserviceTile.class , "color");
EserviceTile eserviceTile2 = random( EserviceTile.class, "color" );
folder.setElements( Arrays.asList(eserviceTile1) );
TileList usersTiles = new TileList( Arrays.asList( folder, eserviceTile2 ) );
userSettingRepository.save( new UserSetting( "user1", usersTiles ));
String string = mvc.perform( get( "/user1" ) ).andExpect( status().isOk() ).andReturn().getResponse().getContentAsString();
Assert.assertThat(string, allOf( containsString( eserviceTile1.getName() ), containsString( eserviceTile2.getName() ) ) );
}
}
If a mongodb is running on default port i see the data persisted. To be independent of running mongo i just added:
testCompile('de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.1.1')
and voila the test runs without mongo! (nothing else to add)
My problem is: I want to disable the embedded Mongo for certain tests. What is the easiest way to achieve that?
Solution
Embedded Mongo daemon is started with EmbeddedMongoAutoConfiguration
. You can disable daemon start in a single test by excluding EmbeddedMongoAutoConfiguration
from scan:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration")
public class DoNotStartMongoTest {
//...
@Test
public void test() {
}
}
I would prefer an opposite functionality: start embedded Mongo daemon on demand. To do this you need to exclude EmbeddedMongoAutoConfiguration
in production code:
@EnableMongoRepositories
@SpringBootApplication(exclude = EmbeddedMongoAutoConfiguration.class)
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
Then in test code add annotation which will enable embedded Mongo daemon start:
@Retention(RUNTIME)
@Target(TYPE)
@Import(EmbeddedMongoAutoConfiguration.class)
public @interface EnableEmbeddedMongo {
}
And annotate your test:
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableEmbeddedMongo
public class StartMongoTest {
//...
@Test
public void test() {
}
}
Answered By - Vitaly