私のアプリケーションは、たMyServiceクラスによってMyPojoクラスにロードMyPojo.json、
という設定ファイルを見つけることを期待:それは存在していない場合、それは問題ではない@PropertySourceを挿入した.propertiesファイルを@Configurationにモックする方法は?
@Data // (Lombok's) getters and setters
public class MyPojo {
int foo = 42;
int bar = 1337;
}
を:その場合、アプリケーションはデフォルト値でそれを作成します。
/src/main/resources/settings.properties
に格納されMyPojo.json書き込み/ を読み取るためにパス:
@PropertySource
介しMyServiceでに渡され the.path=cfg/MyPojo.json
:
@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
です。
それをするために、私は
the.path=build/cfg/MyPojo.json
を含む、のsrc /テスト/リソース下二settings.propertiesにを作成したとせずに、いくつかの方法でたMyServiceにそれを養うために試してみました成功。 テストケースが呼び出されても、MyServiceは常にsrc/test/resources/settings.properties
の代わりにsrc/main/resources/settings.properties
となります。 2つのlog4j2.xml
資源を活用し ではなく(src/main/resources/log4j2.xml
とsrc/test/resources/log4j2-test.xml
)、それが働いた:/
私は@PropertySource
と春で注入されたプロパティファイルで同じことを行うことができますか?