【问题标题】:Spring Boot Test doesn't load complex configuration propertiesSpring Boot Test 不加载复杂的配置属性
【发布时间】:2021-05-07 23:58:12
【问题描述】:

我在 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

【问题讨论】:

    标签: spring-boot spring-boot-test spring-boot-configuration


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-10
      • 2018-08-03
      • 1970-01-01
      • 2020-06-05
      • 2019-05-19
      • 2020-06-14
      • 2016-12-07
      • 2014-12-21
      相关资源
      最近更新 更多