在Junit中运行时发生异常

时间:2018-09-13 19:01:37

标签: java unit-testing junit mockito

我正在尝试对JSONException进行单元测试。下面是代码:

public void testException(JSONObject jsonObj){
    try{
        String test = jsonObj.getString("test");
    }catch(JSONException e){
   }
}

但是在单元测试中,当我给出下面的内容时,它将引发不同的异常:

@Test (expected=JSONException.class){
    mymockClass.testException(jsonObj);
}

java.lang.AssertionError: Expected exception: org.codehaus.jettison.json.JSONException
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

2 个答案:

答案 0 :(得分:2)

这是因为测试期望该异常实际上会从测试方法中抛出,但是您正在捕获它-这就是为什么您有“未抛出预期的异常”异常的原因。删除try-catch块并将throws添加到方法签名。

public void testException(JSONObject jsonObj) throws JSONException{
        String test = jsonObj.getString("test");
}

答案 1 :(得分:0)

引发异常并删除try catch块。

public void testException(JSONObject jsonObj) throws JSONException {
    String test = jsonObj.getString("test");
}

抛出异常,在调用函数中抛出异常。