我想为@NotNull
,@NotEmpty
验证@ConfigurationProperties
写一个测试。
@Configuration
@ConfigurationProperties(prefix = "myPrefix", ignoreUnknownFields = true)
@Getter
@Setter
@Validated
public class MyServerConfiguration {
@NotNull
@NotEmpty
private String baseUrl;
}
我的测试看起来像这样:
@RunWith(SpringRunner.class)
@SpringBootTest()
public class NoActiveProfileTest {
@Test(expected = org.springframework.boot.context.properties.bind.validation.BindValidationException.class)
public void should_ThrowException_IfMandatoryPropertyIsMissing() throws Exception {
}
}
当我运行测试时,它会在测试运行之前报告无法启动应用程序:
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'myPrefix' to com.xxxxx.configuration.MyServerConfiguration$$EnhancerBySpringCGLIB$$4b91954c failed:
我怎么能期望一个Exception写一个负面测试?即使我用BindException.class
替换Throwable.class
,应用程序也无法启动。
尝试以编程方式加载Spring Boot Application上下文:
简单版
public class AppFailIT {
@Test
public void testFail() {
try {
new AnnotationConfigServletWebServerApplicationContext(MyApplication.class);
}
catch (Exception e){
Assertions.assertThat(e).isInstanceOf(UnsatisfiedDependencyException.class);
Assertions.assertThat(e.getMessage()).contains("nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties");
return;
}
fail();
}
}
扩展版本,能够从application-test.properties加载环境,并在方法级别上添加自己的键:值到测试环境:
@TestPropertySource("classpath:application-test.properties")
public class AppFailIT {
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
private ConfigurableEnvironment configurableEnvironment;
@Test
public void testFail() {
try {
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.withProperty("a","b");
configurableEnvironment.merge(mockEnvironment);
AnnotationConfigServletWebServerApplicationContext applicationContext = new AnnotationConfigServletWebServerApplicationContext();
applicationContext.setEnvironment(configurableEnvironment);
applicationContext.register(MyApplication.class);
applicationContext.refresh();
}
catch (Exception e){
Assertions.assertThat(e.getMessage()).contains("nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties");
return;
}
fail();
}
}