kotlinmockitoandroid-unit-testing

android, why after covert to kotlin the unit test fail


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.


Solution

  • The Java code uses the primitive type boolean for value. The Kotlin version is using the nullable type Boolean? which seems unnecessary since the parameter could never be null in the Java version.

    The change to a nullable type might cause the anyBoolean matcher to fail. You could try switching to the non-nullable type Boolean, or keep using Boolean? and change the anyBoolean matcher to anyOrNull from mockito-kotlin.