1

我在 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值设置正确,它也是 null)

@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

4

1 回答 1

0

测试中缺少此注释:@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);
    }

}
于 2021-02-04T09:39:24.333 回答