Spring Boot Test 不加载复杂的配置属性

问题描述

我在 Spring Boot 应用程序中有以下 yaml 配置:

document-types:
  de_DE:
    REPORT: ["Test"]

这是使用以下类加载的,并且在 SpringBootApplication 启动时运行良好(您可以调试 DemoApplication.java 来验证):

@Component
@ConfigurationProperties
@Data
public class DocumentTypeConfiguration {

    private Map<String,Map<String,List<String>>> documentTypes;

}

但是当我执行以下测试时,documentTypes 没有加载(即使 someSrting 值设置正确,它也是空的)

@SpringBoottest(classes = {DocumentTypeConfiguration.class,DocumentTypeService.class})
class DocumentTypeServiceTest {

    @Autowired
    private DocumentTypeConfiguration documentTypeConfiguration;

    @Value("${test}")
    private String someSrting;

    @Autowired
    private DocumentTypeService documentTypeService;

    @Test
    void testFindDocumentType() {
        String documentType = "Test";
        String result = documentTypeService.getDocumentType(documentType);
        String expected = "this";
        assertEquals(expected,result);
    }

}

知道我做错了什么吗?或者 SpringBoottest 不支持属性的复杂类型?

代码和测试可以在这里找到:https://github.com/nadworny/spring-boot-test-properties

解决方法

测试中缺少此注释:@EnableConfigurationProperties

所以测试类看起来像这样:

@SpringBootTest(classes = {DocumentTypeConfiguration.class,DocumentTypeService.class})
@EnableConfigurationProperties(DocumentTypeConfiguration.class)
class DocumentTypeServiceTest {

    @Autowired
    private DocumentTypeConfiguration documentTypeConfiguration;

    @Value("${test}")
    private String someSrting;

    @Autowired
    private DocumentTypeService documentTypeService;

    @Test
    void testFindDocumentType() {
        String documentType = "Test";
        String result = documentTypeService.getDocumentType(documentType);
        String expected = "this";
        assertEquals(expected,result);
    }

}