【问题标题】:How to mock this JSONObject using PowerMockito?如何使用 PowerMockito 模拟这个 JSONObject?
【发布时间】:2017-05-08 01:23:48
【问题描述】:

我的任务是为下面的这个方法编写一个单元测试。但是,我对整个模拟和/或使用 PowerMockito 还是很陌生。方法是这样的:

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 在运行完该方法后是否包含那些额外的键和值。这可能很简单,但我不知道如何开始。

非常感谢任何帮助。

【问题讨论】:

  • 什么是JSONMockTest?您应该将JSONObject 作为方法参数传递。

标签: json unit-testing junit mocking powermockito


【解决方案1】:

只要您的方法不是私有的,您就不需要使用Whitebox.invokeMethod。 来自Whitebox.invokeMethod javadoc

调用静态私有或内部类方法。这可能对 测试私有方法。

直接调用即可:

JSONObject resultJsonObject = Storage.addHeader(jsonObject);

现在您可以断言resultJsonObject 的值。

【讨论】:

  • 原来我不需要像上面建议的那样使用 Whitebox.invokeMethod。而且我还发现了值总是返回 null 的原因是因为我在整个班级都有 mockStatic。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 2017-04-30
相关资源
最近更新 更多