在Android JUnit

时间:2018-01-16 12:32:06

标签: java android unit-testing junit mockito

我正在尝试模拟在另一个函数中调用的函数。但我得到的最终结果为null。我试图模拟在实际函数中使用的第二个函数。

这是我的代码:

@RunWith(MockitoJUnitRunner.class)
public class LoadJsonData_Test {

@Mock
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();
    }
    when(loadJsonData.getJsonData()).thenReturn(jsonStr);

    System.out.println(loadJsonData.getJsonData()); //Printing the data I wanted
    assertEquals(loadJsonData.getChartTypeJS(), 
"javascript:setChartSeriesType(%d);"); // loadJsonData.getChartTypeJS() returns null

}

我正试图测试的代码:

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 "";
}

我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

您正在模仿LoadJsonData,然后在其上调用两个方法:

  • getJsonData()
  • getChartTypeJS()

您可以在此处getJsonData()创建对响应的期望:

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

但由于模拟对getChartTypeJS()的响应没有期望,因此该调用返回null:loadJsonData.getChartTypeJS()

看起来LoadJsonData应该是Spy而不是Mock,因为这样可以模拟getJsonData(),但会调用getChartTypeJS()的实际实现。

例如:

@Spy
LoadJsonData loadJsonData;

// this wil tell Mockito to return jsonStr when getJsonData() is invoked on the spy
doReturn(jsonStr).when(loadJsonData.getJsonData());

// this will invoke the actual implementation
assertEquals(loadJsonData.getChartTypeJS(), "javascript:setChartSeriesType(%d);");

关于间谍活动的更多细节(又名部分嘲笑)here

相关问题