Tan*_*MUC 5 spring-boot spring-boot-test
我想编写一个测试来@NotNull验证.@NotEmpty@ConfigurationProperties
@Configuration
@ConfigurationProperties(prefix = "myPrefix", ignoreUnknownFields = true)
@Getter
@Setter
@Validated
public class MyServerConfiguration {
@NotNull
@NotEmpty
private String baseUrl;
}
Run Code Online (Sandbox Code Playgroud)
我的测试如下所示:
@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 {
}
Run Code Online (Sandbox Code Playgroud)
}
当我运行测试时,它报告在测试运行之前启动应用程序失败:
***************************
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:
Run Code Online (Sandbox Code Playgroud)
我如何期望异常会编写负面测试?即使我将其替换BindException.class为Throwable.class应用程序也无法启动。
pop*_*lka -1
尝试以编程方式加载 Spring Boot 应用程序上下文:
简易版
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();
}
}
Run Code Online (Sandbox Code Playgroud)
扩展版本 能够从 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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1889 次 |
| 最近记录: |