【发布时间】: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.xml 和 src/test/resources/log4j2-test.xml),它起作用了:/
我可以对 Spring 使用 @PropertySource 注入的属性文件执行相同的操作吗?
【问题讨论】:
标签: java spring unit-testing junit mocking