使用mockito 3.8.0,拥有一个类Util:
class Util {
static JSONObject addKeyToJson_booleanValue(@NonNull JSONObject jsonObject, @NonNull String key, boolean value) {
try {
System.out.println("+++ +++ enter addKeyToJson(), jsonObject:"+jsonObject+", key:"+key+", val:"+value);
jsonObject.put(key, value);
} catch (JSONException e) {
System.out.println("+++ +++ !!! exp addKeyToJson(), jsonObject:"+jsonObject+", key:"+key+", val:"+value+", ex:"+e.toString());
e.printStackTrace();
}
return jsonObject;
}
}
测试
@Test
public void test_addKeyToJson_boolean_value() throws JSONException {
JSONObject jsonObjectSpy = Mockito.spy(new JSONObject());
Mockito.when(jsonObjectSpy.put(anyString(), anyBoolean())).thenThrow(new JSONException("!!! test forced exception"));
JSONObject outputObject = Util.addKeyToJson_booleanValue(jsonObjectSpy, "null", true);
assertEquals(0, outputObject.length()); //<=== fail
}
人们认为Mockito.when(jsonObjectSpy.put(anyString(), anyBoolean())).thenThrow(new JSONException("!!! test forced exception"));
是一个设置,用于在调用jsonObject.put("null", true)
时抛出,因此返回的jsonObject应该仍然为空。
但测试失败了,并注意到当addKeyToJson(@NonNull JSONObject jsonObject, @NonNull String key, boolean value)
被调用时,jsonObjectSpy
已经有一对{",false"}。日志
+++ +++ enter addKeyToJson(), jsonObject:{"":false}, key:null, val:true
+++ +++ !!! exp addKeyToJson(), jsonObject:{"":false}, key:null, val:true, ex:org.json.JSONException: !!! test forced exception
并且它确实抛出了异常。问题是为什么
Mockito.when(jsonObjectSpy.put(anyString(), anyBoolean())).thenThrow(new JSONException("!!! test forced exception"));
实际上把{"":false}
放在jsonObjectSpy
中?
但是,当值需要一个String时,它可以很好地与Mockito.when(jsonObjectSpy.put(anyString(), any())).thenThrow(new JSONException("!!! fake exception"));
配合使用。
static JSONObject addKeyToJson_stringValue(@NonNull JSONObject jsonObject, @NonNull String key, @NonNull String value) {
try {
jsonObject.put(key, value);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
===
@Test
public void test_addKeyToJson_stringValue() throws Exception {
JSONObject jsonObjectSpy = Mockito.spy(new JSONObject());
Mockito.when(jsonObjectSpy.put(anyString(), any())).thenThrow(new JSONException("!!! fake exception"));
Util.addKeyToJson_stringValue(jsonObjectSpy, "key", "value");
assertEquals(0, jsonObjectSpy.length());
}
似乎是
Mockito.when(jsonObjectSpy.put(anyString(), any())).thenThrow(new JSONException("!!! fake exception"));
使用any()
实际上不会将键/值对放在jsonObjectSpy中,但使用anyString()
或anyBoolean()
会将键/价值对放在jsonObjectSpy。
必须在Mockito.when(jsonObjectSpy.put(anyString(), anyBoolean())).thenThrow(new JSONException("!!! fake exception"));
之后执行jsonObjectSpy.remove(anyString())
才能使jsonObjectSpy再次为空。