我基于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 。最简单的方法是什么?
答案 0 :(得分:6)
嵌入式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() {
}
}