Java 如何在JUnit测试中测试JSONException?

Java 如何在JUnit测试中测试JSONException?,java,junit,Java,Junit,我想用下面的方法测试JSONException,但无法实现。以下是我的实施: methodA中的方法formatresponse已将键(UtilClass.Object.YEAR)添加到JSONObject,因此,键不可能不存在,因为类中没有其他方法来移除键。我曾经尝试过使用mockito框架进行mocking来抛出JSONException,但是使用thenthorn或doThrow来抛出异常都没有成功 private JSONObject response; public ReturnTy

我想用下面的方法测试JSONException,但无法实现。以下是我的实施:

methodA
中的方法
formatresponse
已将键(UtilClass.Object.YEAR)添加到JSONObject,因此,键不可能不存在,因为类中没有其他方法来移除键。我曾经尝试过使用mockito框架进行mocking来抛出JSONException,但是使用
thenthorn
doThrow
来抛出异常都没有成功

private JSONObject response;

public ReturnType methodA(JsonObject request, String ipAddr) {

      formatResponse(UtilClass.Object.YEAR, new JSONObject());

      for (int i = 0; i < computedYear.length; i++) {

         try {
              response.getJSONObject(UtilClass.Object.YEAR).put(computedYear[i], new JSONObject()); <== How do I unit test for this line?
         } catch (JSONException e) {
              System.out.println(e.getMessage())
         }

}

private void formatResponse(String key, Object value) {
     try {
         response.put(key, value);
     } catch (JSONException e) {
         e.printStackTrace();
     }
}


如果您以前遇到过以下问题,我将非常感谢您提供任何形式的帮助或分享知识。谢谢大家!

请共享junit代码。在junit中,
response
的值是多少?我已经在junit测试中添加了。在本例中,响应是{“year”{},UtilClass.Object.year值是“year”,如果您使用
响应
,例如
{}
,并且不模拟任何内容会怎么样?这不可能,正如我上面所写的那样。methodA中的formatresponse方法已将键(UtilClass.Object.YEAR)添加到JSONObject中,因此,该键不可能不存在,因为类中没有其他方法可以删除该键。调用getJSONObject时,可以模拟响应对象并抛出JSONException。请共享junit代码。在junit中,
response
的值是多少?我已经在junit测试中添加了。在本例中,响应是{“year”{},UtilClass.Object.year值是“year”,如果您使用
响应
,例如
{}
,并且不模拟任何内容会怎么样?这不可能,正如我上面所写的那样。methodA中的formatresponse方法已将键(UtilClass.Object.YEAR)添加到JSONObject,因此,该键不可能不存在,因为类中没有其他方法可以删除该键。调用getJSONObject时,可以模拟响应对象并抛出JSONException
private String ipAddr = "127.0.0.1";

public void testMethodA() {

     ClassA classAInstance = mock(ClassA.class);
     Mockito.doThrow(JSONException.class).when(classAInstance).methodA(request, ipAddr);

     classInstance.methodA(request, ipAddr);
}