2017-10-30 4 views
0

私のアプリケーションは、た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書き込み/ を読み取るためにパス:

次のようにSpringの@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.xmlsrc/test/resources/log4j2-test.xml)、それが働いた:/

私は@PropertySourceと春で注入されたプロパティファイルで同じことを行うことができますか?

答えて

1

@TestPropertySourceアノテーションを使用できます。

例:単一のプロパティについては :

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

プロパティファイルについて

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

だから、あなたは

@TestPropertySource(properties = "path=build/cfg/MyPojo.json") 
ようMyPojo.jsonのパスを提供します
関連する問題