Sindhu
Sindhu

Reputation: 451

Getting null as result of a mocked method call in Android JUnit

I am trying to mock a function that is being called within another function. But I am getting end result as null. I tried to mock the second function that is being used in actual function.

Here is my code:

@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

}

Code I am trying to test:

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

What is it I am doing wrong?

Thanks

Upvotes: 0

Views: 799

Answers (1)

glytching
glytching

Reputation: 47905

You are mocking LoadJsonData and then invoking two methods on it:

  • getJsonData()
  • getChartTypeJS()

You create an expectation on the response from getJsonData() here:

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

But since the mock has no expectation for a response from getChartTypeJS() this invocation returns null: loadJsonData.getChartTypeJS().

It looks like LoadJsonData should be a Spy not a Mock since that would allow you to mock getJsonData() but invoke the actual implementation of getChartTypeJS().

For example:

@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);");

More details on spying (aka partial mocks) here.

Upvotes: 2

Related Questions