gpt4 book ai didi

java - 如何使用 Mockito 测试 ClassNotFoundException?

转载 作者:行者123 更新时间:2023-12-01 06:52:40 25 4
gpt4 key购买 nike

我正在对以下类运行单元测试:

public class FileClass {

public void funcB() {
try {
throw new ClassNotFoundException();
}
catch( ClassNotFoundException e ) {

}
}
}

使用Mockito代码如下所示:

public class TestFileClass {

@Test(expected=ClassNotFoundException.class)
public void testFuncB() {
FileClass fc = Mockito.spy(new FileClass());
fc.funcB();
}

}

但是由于以下错误,测试失败:

java.lang.AssertionError: Expected exception: java.lang.ClassNotFoundException
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:35)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

我也尝试过 PowerMockito 但再次失败。关于这个错误有什么线索吗?在我看来,我无法对 ClassNotFoundException 运行任何测试?

最佳答案

funcB 不会抛出异常,因为您是在 funcB 的主体内捕获它。

关于java - 如何使用 Mockito 测试 ClassNotFoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20986195/

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