0

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.

lannyf
  • 9,865
  • 12
  • 70
  • 152
  • 1
    A `Boolean?` corresponds to `@Nullable Boolean` in Java, so `anyBoolean` might not be the correct matcher. – Michael Jan 12 '22 at 14:13
  • 1
    In this case it might be an incorrect translation from Java to Kotlin. The Java code used the primitive `boolean` which can't be `null`, so `Boolean` without the `?` ought to work in the Kotlin code. If you still want it to be nullable, then perhaps you can use the `anyOrNull` matcher from mockito-kotlin. – Michael Jan 12 '22 at 14:21
  • 1
    @Michael, you are right. the kotlin code maps the jsonObject.put(key, value) to `JSONObject put(@NonNull String name, @Nullable Object value)` when it sees the value: Boolean?. If you put in as an answer I will accept it. Thanks! – lannyf Jan 12 '22 at 14:24

1 Answers1

1

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.

Michael
  • 57,169
  • 9
  • 80
  • 125