【问题标题】:How to mock a .properties file injected with @PropertySource in @Configuration?如何模拟在@Configuration 中注入@PropertySource 的.properties 文件?
【发布时间】:2017-10-30 16:59:03
【问题描述】:

我的应用程序希望找到一个名为 MyPojo.json 的配置文件,
MyService 类加载到 MyPojo 类中:

@Data // (Lombok's) getters and setters
public class MyPojo {
    int foo = 42;
    int bar = 1337;
}

如果它不存在也没关系:在这种情况下,应用程序将使用默认值创建它。

读取/写入MyPojo.json的路径存放在/src/main/resources/settings.properties:

the.path=cfg/MyPojo.json

通过Spring的@PropertySource传递给MyService如下:

@Configuration
@PropertySource("classpath:settings.properties")
public class MyService {

    @Inject
    Environment settings; // "src/main/resources/settings.properties"

    @Bean
    public MyPojo load() throws Exception {
        MyPojo pojo = null;

        // "cfg/MyPojo.json"
        Path path = Paths.get(settings.getProperty("the.path")); 

        if (Files.exists(confFile)){ 
            pojo = new ObjectMapper().readValue(path.toFile(), MyPojo.class);
        } else {    // JSON file is missing, I create it. 
            pojo = new MyPojo();
            Files.createDirectory(path.getParent()); // create "cfg/"
            new ObjectMapper().writeValue(path.toFile(), pojo); // create "cfg/MyPojo.json"
        }

        return pojo;
    }
}

由于 MyPojo 的路径是相对的,所以当我从单元测试中运行它时

@Test   
public void testCanRunMockProcesses() {

    try (AnnotationConfigApplicationContext ctx = 
          new AnnotationConfigApplicationContext(MyService.class)){

        MyPojo pojo = ctx.getBean(MyPojo.class);

        String foo = pojo.getFoo();
        ...
        // do assertion
    }       
}

cfg/MyPojo.json是在我项目的root下创建的,这绝对不是我想要的。

我希望在我的 target 文件夹下创建 MyPojo.json
例如。 /build 在 Gradle 项目中,或 /target 在 Maven 项目中。

为此,我在 src/test/resources 下创建了一个辅助 settings.properties,其中包含

the.path=build/cfg/MyPojo.json

并尝试通过多种方式将其提供给 MyService,但均未成功。 即使被测试用例调用,MyService 总是读取src/main/resources/settings.properties 而不是src/test/resources/settings.properties

使用两个 log4j2.xml 资源(src/main/resources/log4j2.xmlsrc/test/resources/log4j2-test.xml),它起作用了:/

我可以对 Spring 使用 @PropertySource 注入的属性文件执行相同的操作吗?

【问题讨论】:

    标签: java spring unit-testing junit mocking


    【解决方案1】:

    您可以为此使用 @TestPropertySource 注释。

    示例: 对于单一属性:

    @TestPropertySource(properties = "property.name=value")
    

    对于属性文件

    @TestPropertySource(
      locations = "classpath:yourproperty.properties")
    

    所以,你为 MyPojo.json 提供路径

    @TestPropertySource(properties = "path=build/cfg/MyPojo.json")
    

    【讨论】:

    • 上课前需要写这个吗?
    • 这个注解将用于类 For 例如@TestPropertySource(properties = "path=build/cfg/MyPojo.json") public class MyTest {...//你的代码}
    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多