2017-05-30 26 views
0

testngとjmockitを組み合わせてユニットテストを行う。私がテストしているメソッドでは、JBossデプロイスクリプトを使用して設定したシステムプロパティにアクセスしようとします。そのため、私の単体テストはJBoss環境全体にアクセスしてプロパティにアクセスすることはできません。 。私のテストでは、黙ってシステム変数を直接設定しようとしましたが、テスト中のクラスでシステムプロパティはnullを返しています。jmockitユニットテストでシステムプロパティを設定する

クラスは、試験される:

//returns the correct value in the application but returns null for the test 
public static final String webdavrootDir = System.getProperty("property.name"); 

public String getFileUrl(){ 
     StringBuilder sb = new StringBuilder(); 
     return sb.append(webdavrootDir) 
       .append(intervalDir) 
       .append(fileName) 
       .toString(); 
} 

テスト:テスト値null/otherstuffが見つかったが、私はまた、TestNGのシステムプロパティを設定しようとしているhttps://justatest.com/dav/bulk/otherstuff

期待

@Test 
    public void getUrl(@Mocked System system){ 
     system.setProperty("property.name", "https://justatest.com/dav/bulk"); 
     String fileUrl = csvConfig.getFileUrl(); 

     assertEquals(fileUrl, "https://justatest.com/dav/bulk/otherstuff"); 
} 

@BeforeMethodメソッドは成功しません。

答えて

3

テスト対象のクラスがインスタンス化される前にSystem.setProperty("property.name", "https://justatest.com/dav/bulk");に電話してください。そうでない場合は、静的フィールドは常にnullになります。あなたがjMockiを使用したい場合は、

@BeforeClass 
public void setup() { 
    System.setProperty("property.name", "https://justatest.com/dav/bulk"); 
    // Instantiate your CsvConfig instance here if applicable. 
} 

@Test 
public void getUrl(){ 
    System.setProperty("property.name", "https://justatest.com/dav/bulk"); 
    String fileUrl = csvConfig.getFileUrl(); 
    assertEquals(fileUrl, "https://justatest.com/dav/bulk/otherstuff"); 
} 
1

を、あなたはそれがあなたのクラス - の前に、行われていることを確認する必要があります。

このため@BeforeClass設定方法を使用することを検討してくださいアンダーテストは静的フィールドのためにロードされます。

@BeforeClass 
public static void fakeSystemProperty() { 
    new MockUp<System>() { 

     @Mock 
     public String getProperty(String key) { 
      return "https://justatest.com/dav/bulk"; 
     } 
    }; 
} 

別の方法は、例えば、クラス被試験を変更し、部分的にこれを模擬することであろう:

public class CsvConfig { 
    private static final String webdavrootDir = System.getProperty("property.name"); 

    public static String getProperty() { 
     return webdavrootDir; 
    } 
} 

試験:

@BeforeClass 
public static void fakeSystemProperty() { 
    new MockUp<CsvConfig>() { 

     @Mock 
     public String getProperty() { 
      return "https://justatest.com/dav/bulk"; 
     } 
    }; 
} 
関連する問題