我在发送无效的JSON的地方进行了测试,它应该捕获到一个JSONException

当我运行测试时,它失败并显示JSONException,为什么测试没有捕获到它?

@Test (expected = JSONException.class)
public void testExtraFieldsJsonException() {
    String json = "wrong_data";
    fragment.decodeJson(json);
}


我使用org.json.JSONException。

测试结果。

org.json.JSONException: Value wrong_data of type java.lang.String cannot be converted to JSONObject
    at org.json.JSON.typeMismatch(JSON.java:111)
    at org.json.JSONObject.<init>(JSONObject.java:158)
    at org.json.JSONObject.<init>(JSONObject.java:171)
    at co.some.mainactivities.ProfileFragment.extraFields(ProfileFragment.java:154)
    at co.some.mainactivities.ProfileFragment.callExtraFields(ProfileFragment.java:243)
    at co.some.mainactivities.TestProfileFragment.testExtraFieldsJsonException(TestProfileFragment.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)


它在new JSONObject(json);中失败

private void decodeJson(String json) {
    try {
     JSONObject json = new JSONObject(json);
     int fieldsQuantity = json.getJSONObject("extra_fields").length();
     //....
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
}

最佳答案

您正在decodeJSON中捕获异常,因此它不会传播到测试。

如果要将异常抛出给decodeJSON的调用者(例如测试),请删除try-catch并将throws JSONException添加到函数签名中。

08-26 02:21