2017-05-08 380 views
0

我的任務是爲這個方法編寫一個單元測試。不過,我對整個嘲笑和/或使用PowerMockito還是比較陌生的。這是方法:如何使用PowerMockito模擬此JSONObject?

public class Storage { 
    public static JSONObject addHeader(JSONObject input) throws JSONException { 
      try { 
       JSONObject header = new JSONObject(); 
       header.put("update_date", System.currentTime()); 
       header.put("created_date", System.currentTime()); 
       header.put("type", "storage"); 
       input.put("HEADER", header); 
      } 
      catch (JSONException e) { 
       e.printStackTrace(); 
      }      
      return input; 
} 

而這就是我卡住的地方。在我的測試方法中,我有這一行代碼。

JSONObject testInput = Whitebox.invokeMethod(Storage, "addHeader", JSONMockTest()); 
//testInput is always return null so this is where I'm stuck at and as not sure what to do after this 

我想驗證返回的JSONMockTest在運行該方法後將包含那些額外的鍵和值。這可能很簡單,但我不知道如何開始。

任何幫助,非常感謝。

+0

什麼是'JSONMockTest'?您應該傳遞'JSONObject'作爲方法參數。 –

回答

0

只要你的方法不是私人的,你不需要使用Whitebox.invokeMethod。 從Whitebox.invokeMethod javadoc

調用靜態私有或內部類方法。這可能對 測試私有方法有用。

只需直接調用它:

JSONObject resultJsonObject = Storage.addHeader(jsonObject); 

現在可以斷言的resultJsonObject值。

+0

原來我不需要使用上面建議的Whitebox.invokeMethod。而且我還發現值總是返回null的原因是因爲我對整個類都進行了mockStatic。謝謝你的幫助。 –

相關問題