【问题标题】:How to use JSONObjects in writing local tests using junit mockito如何使用 JSONObjects 使用 junit mockito 编写本地测试
【发布时间】:2018-01-16 14:03:37
【问题描述】:

我有一个使用 JSONObject 的函数,我需要对其进行测试。这是我的代码:

这是我要测试的代码:

public String getJsonData() {
try {
    InputStream is = mContext.getAssets().open("chartInfo.json");
    int size = is.available();
    byte[] buffer = new byte[size];
    if (is.read(buffer) > 0)
        jsonString = new String(buffer, "UTF-8");
    is.close();

} catch (IOException ex) {
    ex.printStackTrace();
    return null;
}
return jsonString;
}

public String getChartTypeJS() {
jsonString = getJsonData();
try {
    JSONObject jsonObject = new JSONObject(jsonString);
    JSONObject javascriptEvent_JsonObject = jsonObject.getJSONObject("javascript_events");
    return javascriptEvent_JsonObject.getString("chartType");
} catch (JSONException e) {
    e.printStackTrace();
}
return "";
}

我的测试代码:

@RunWith(MockitoJUnitRunner.class)
public class LoadJsonData_Test {

@Spy
private LoadJsonData loadJsonData;

@Test
public void getChartTypeJS_test() {

    String jsonStr = "";
    try {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("chartInfo.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        if (is.read(buffer) > 0)
            jsonStr = new String(buffer, "UTF-8");
        is.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    doReturn(jsonStr).when(loadJsonData).getJsonData();
    assertEquals(loadJsonData.getChartTypeJS(), "javascript:setChartSeriesType(%d);");

    }

}

引发错误: java.lang.RuntimeException:org.json.JSONObject 中的 getJSONObject 方法未模拟。详情请见http://g.co/androidstudio/not-mocked。

如您所见,我正在使用 JSONObjets 从 json 文件中获取数据。我们如何测试上述函数的结果?

谢谢

【问题讨论】:

  • 你分享完整的 LoadJsonData 类吗?

标签: java android unit-testing junit mockito


【解决方案1】:

将这一行添加到 Android build.gradle 解决了这个问题:

testCompile "org.json:json:20140107"

【讨论】:

    【解决方案2】:

    为了使该方法更易于测试,您可以将jsonString 作为参数传递:

    public String getChartTypeJS(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject javascriptEvent_JsonObject = jsonObject.getJSONObject("javascript_events");
            return javascriptEvent_JsonObject.getString("chartType");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        return "";
    }
    

    那么在你的测试中你就不需要这行了:

    doReturn(jsonStr).when(loadJsonData).getJsonData();
    

    【讨论】:

    • 会的,因为您不需要在测试中调用getJSONObject。您应该在单独的单元测试中测试方法
    • 它仍然抛出同样的错误,因为我在 assertEquals 中调用 getChartTypeJS() 函数
    • 删除这一行@Spy private LoadJsonData loadJsonData;你需要创建一个被测类的新实例。
    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2019-06-21
    • 2018-10-06
    相关资源
    最近更新 更多