我有一些特定于测试的AutoConfiguration
,我想在同一个测试类中编写多个测试。我认为Boot 2.0+中的新ApplicationContextRunner
可能是实现这一目标的一个很好的候选者,但看起来这只是为了测试正常的启动自动配置,而不是通过TestExecutionListener
来实现的。其余的Spring Test上下文支持。
对于我的具体示例,我试图在有人使用@WebMvcTest
时添加一些Spring Security测试配置。我想成为一个好公民,并在spring.test.mockmvc.secure=false
时退出,就像MockMvcSecurityAutoConfiguration
一样。这就是我所拥有的:
spring.factories:
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc=\
com.broadleafcommerce.test.common.security.SecurityHelperConfig
SecurityHelperConfig:
@Configuration
@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure", havingValue = "true", matchIfMissing = true)
public class MockOauth2ResourceServerConfig {
@Bean
public String someBean() {
return "hello";
}
}
验证这一点的测试非常简单并且运行正常:
@RunWith(SpringRunner.class)
@WebMvcTest
public class TestAutoConfigs {
@SpringBootConfiguration
static class EmptyBootConfig {}
@Autowired
ApplicationContext ctx;
@Test
public void foundAutoConfig() {
assertNotNull(ctx.getBean("someBean"));
}
}
为了测试相反的情况,我可以创建另一个@WebMvcTest(secure = false)
的测试类。
但是,我希望我能做到这样的事情:
public class TestAutoConfigs {
@WebMvcTest
static class SecureEnabled {
@SpringBootConfiguration
static class EmptyBootConfig {}
}
@WebMvcTest(secure = false)
static class SecureDisabled {
@SpringBootConfiguration
static class EmptyBootConfig {}
}
@Test
public void testBeanFoundWhenSecure() {
new WebApplicationContextRunner()
.withUserConfiguration(SecureEnabled.class)
.run((ctx) -> {
assertNotNull(ctx.getBean("someBean"));
});
}
@Test
public void testBeanNotFoundWhenNotSecure() {
new WebApplicationContextRunner()
.withUserConfiguration(SecureDisabled.class)
.run((ctx) -> {
assertNull(ctx.getBean("someBean"));
});
}
}
我是否有任何设施可以像某种TestContextRunner