![](/img/trans.png)
[英]Configuring flapdoodle embedded mongo with Mongodb version 4 and replica
[英]How to disable flapdoodle embedded mongodb in certain tests
我基于Spring Initializr (渐变风味)创建了一个Spring Boot应用程序。
我还加了
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
使用MongoDB进行持久化。 我还添加了一个可以正常工作的简单集成测试:
@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() ) ) );
}
}
如果mongodb在默认端口上运行,我看到数据仍然存在。 为了独立于运行mongo,我刚刚添加了:
testCompile('de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.1.1')
瞧,测试无需mongo! (没什么可补充的)
我的问题是: 我想对某些测试禁用嵌入式Mongo 。 最简单的方法是什么?
嵌入式Mongo守护程序从EmbeddedMongoAutoConfiguration
启动。 您可以通过从扫描中排除EmbeddedMongoAutoConfiguration
来禁用单个测试中的守护程序启动:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration")
public class DoNotStartMongoTest {
//...
@Test
public void test() {
}
}
我更喜欢相反的功能:按需启动嵌入式Mongo守护程序。 为此,您需要在生产代码中排除EmbeddedMongoAutoConfiguration
:
@EnableMongoRepositories
@SpringBootApplication(exclude = EmbeddedMongoAutoConfiguration.class)
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
然后在测试代码中添加注释,这将使嵌入式Mongo守护程序启动:
@Retention(RUNTIME)
@Target(TYPE)
@Import(EmbeddedMongoAutoConfiguration.class)
public @interface EnableEmbeddedMongo {
}
并注释您的测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableEmbeddedMongo
public class StartMongoTest {
//...
@Test
public void test() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.