如何在使用Junit Mockito编写本地测试中使用JSONObjects [英] How to use JSONObjects in writing local tests using junit mockito

查看:670
本文介绍了如何在使用Junit Mockito编写本地测试中使用JSONObjects的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function using JSONObject, which I need to test . Here is my code:

这是我要测试的代码:

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 .


Error thrown: java.lang.RuntimeException: Method getJSONObject in org.json.JSONObject not mocked. See http://g.co/androidstudio/not-mocked for details.

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

As you can see I am using JSONObjets to get data from json file. How can we test the outcome of the above functions?

谢谢

推荐答案

将此行添加到Android build.gradle 解决了该问题:

Adding this line to Android build.gradle solved the issue:

testCompile "org.json:json:20140107"

这篇关于如何在使用Junit Mockito编写本地测试中使用JSONObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆