gpt4 book ai didi

java - 在 Junit 中运行时出现异常

转载 作者:行者123 更新时间:2023-11-30 02:02:41 31 4
gpt4 key购买 nike

我正在尝试对 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)

最佳答案

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

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

关于java - 在 Junit 中运行时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52320202/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com