On android app, Having a java function
JSONObject addToJson(@NonNull JSONObject jsonObject, @NonNull String key, boolean value){
try {
jsonObject.put(key, value);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
test code, it throws when call the mock jsonObject.put(key, value) and works fine:
@Test
public void test_addToJson() throws JSONException {
JSONObject jsonObject = Mockito.spy(new JSONObject());
Mockito.when(jsonObject.put(anyString(), anyBoolean())).thenThrow(new JSONException("!!! test forced exception"));
JSONObject outputObject = addToJson(jsonObject, "null", true);
assertEquals("jsonobject length should match", 0, outputObject.length());
}
after convert to kotlin
fun addToJson(jsonObject: JSONObject, key: String, value: Boolean?): JSONObject {
try {
jsonObject.put(key, value)
} catch (e: JSONException) {
e.printStackTrace()
}
return jsonObject
}
the test is failing that no exception thrown.