如何模拟在@Configuration中注入@PropertySource的.properties文件



我的应用程序希望找到一个名为MyPojo.json的配置文件,
MyServiceclass:加载到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是在我的项目的根目录下创建的,这绝对不是我想要的。

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

为此,我在src/test/resources下创建了一个辅助的设置.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注入的属性文件执行同样的操作吗?

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

示例:对于单一属性:

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

对于属性文件

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

因此,您为MyPojo.json提供了类似的路径

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

最新更新