Spring Boot Sping Boot @ConfigurationProperties验证测试失败

p8h8hvxi  于 2022-12-04  发布在  Spring
关注(0)|答案(2)|浏览(208)

我想写一个测试来验证@ConfigurationProperties@NotNull@NotEmpty

@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:

我怎么能期望一个异常编写一个否定的测试呢?即使我用Throwable.class替换BindException.class,应用程序也无法启动。

cygmwpex

cygmwpex1#

我会使用ApplicationContextRunner来表示,例如。

new ApplicationContextRunner()
    .withUserConfiguration(MyServerConfiguration.class)
    .withPropertyValues("foo=bar")
    .run(context -> {
        var error = assertThrows(IllegalStateException.class, () -> context.getBean(MyServerConfiguration.class));

        var validationError = (BindValidationException) ExceptionUtils.getRootCause(error);
        var fieldViolation = (FieldError) validationError.getValidationErrors().iterator().next();
        var fieldInError = fieldViolation.getObjectName() + "." + fieldViolation.getField();

        assertThat(fieldInError, is(expectedFieldInError));
        assertThat(fieldViolation.getDefaultMessage(), is(expectedMessage));
    });
cs7cruho

cs7cruho2#

尝试以编程方式加载Sping 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();
    }
}

扩展版本能够从www.example.com加载环境application-test.properties,并将自己的key:values添加到方法级别的测试环境中:

@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();
    }
}

相关问题