2014-02-05 120 views
1

我無法捕獲靜態方法的參數。靜態方法是所謂的測試方法,然後叫在驗證中第二次阻止,但這次的參數爲空,所以我有一個NullPointerException ...通過靜態方法捕獲驗證

這裏是我的代碼:

@Tested 
private Service testService; 

@Test 
public void test { 

    // Tested method 
    Deencapsulation.invoke(testService, "testMethod"); 

    // Verifications 
    new Verifications() { 
     NotificationsUtils utils; 
     { 
      HashMap<String, Object> map; 
      NotificationsUtils.generateXML(anyString, map = withCapture()); 

      // NullPointerException is thrown here 
      // because in generateXML method map is null and map.entrySet() is used. 
     } 
    }; 

} 

如何當generateXML被調用時,我可以捕獲地圖變量嗎?

感謝

回答

1

顯然,你的測試從未宣佈過NotificationsUtils被嘲笑。 雖然以下完整的示例工程:

static class Service { 
    void testMethod() { 
     Map<String, Object> aMap = new HashMap<String, Object>(); 
     aMap.put("someKey", "someValue"); 

     NotificationsUtils.generateXML("test", aMap); 
    } 
} 

static class NotificationsUtils { 
    static void generateXML(String s, Map<String, Object> map) {} 
} 

@Tested Service testService; 

@Test 
public void test(@Mocked NotificationsUtils utils) { 
    Deencapsulation.invoke(testService, "testMethod"); 

    new Verifications() {{ 
     Map<String, Object> map; 
     NotificationsUtils.generateXML(anyString, map = withCapture()); 
     assertEquals("someValue", map.get("someKey")); 
    }}; 
}