2017-05-08 376 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。谢谢你的帮助。 –

相关问题