如何使用 PowerMockito 模拟这个 JSONObject?
How to mock this JSONObject using PowerMockito?
我受命为下面的这个方法编写单元测试。但是,我对使用 PowerMockito 的整个模拟 and/or 相当陌生。这是方法:
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
我想通过该方法验证 return JSONMockTest 是否包含 运行 之后的那些附加键和值。这可能很简单,但我不确定如何开始。
非常感谢任何帮助。
只要您的方法不是私有的,就不需要使用 Whitebox.invokeMethod
。
来自 Whitebox.invokeMethod javadoc:
Invoke a static private or inner class method. This may be useful to
test private methods.
直接调用即可:
JSONObject resultJsonObject = Storage.addHeader(jsonObject);
现在您可以声明 resultJsonObject
的值。
我受命为下面的这个方法编写单元测试。但是,我对使用 PowerMockito 的整个模拟 and/or 相当陌生。这是方法:
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
我想通过该方法验证 return JSONMockTest 是否包含 运行 之后的那些附加键和值。这可能很简单,但我不确定如何开始。
非常感谢任何帮助。
只要您的方法不是私有的,就不需要使用 Whitebox.invokeMethod
。
来自 Whitebox.invokeMethod javadoc:
Invoke a static private or inner class method. This may be useful to test private methods.
直接调用即可:
JSONObject resultJsonObject = Storage.addHeader(jsonObject);
现在您可以声明 resultJsonObject
的值。