如何使用Mockito测试ClassNotFoundException?
问题描述:
我正在以下课程上运行单元测试:
I'm running unit test on the following class:
public class FileClass {
public void funcB() {
try {
throw new ClassNotFoundException();
}
catch( ClassNotFoundException e ) {
}
}
}
使用Mockito代码,如下所示:
Using Mockito code as shown below:
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
上运行任何测试?
I did also try on PowerMockito but failed again. Any clue with this error? It seems to me that I can't run any test on ClassNotFoundException
?
答
funcB()方法应引发异常,而不是捕获异常。下面的代码和测试工作正常:
The method funcB() should throw the exception, not catch it. The code bellow and test work fine:
public class FileClass {
public void funcB() throws ClassNotFoundException {
//try {
throw new ClassNotFoundException();
//} catch ( ClassNotFoundException e) {
//}
}
}
Mockito测试:
Mockito test:
public class TestFileClass {
@Test(expected = ClassNotFoundException.class)
public void testFuncB() throws ClassNotFoundException {
FileClass fc = Mockito.spy(new FileClass());
fc.funcB();
}
}