我有疑問,類似我previous question在那裏我有下面的類:我怎麼能測試ClassNotFoundException被拋出?
public class FileClass {
public void funcB() throws ClassNotFoundException {
throw new ClassNotFoundException();
}
}
我想測試是否當funcB()
被稱爲ClassNotFoundException
將被拋出。因此,我有這樣的測試代碼:
public class TestFileClass {
@Test(expected=ClassNotFoundException.class)
public void testFuncB() throws ClassNotFoundException {
FileClass fc = Mockito.spy(new FileClass());
Mockito.doThrow(new ClassNotFoundException())
.when(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)
任何線索,我怎麼能在測試funcB()
ClassNotFoundException
?
如果在FileClass構造函數中引發此異常,則此測試將通過。在使用funcB之前,最好使用ExpectedException @Rule並期待異常。 – dzezzz
@dzezzz好點。 'ClassNotFoundExcepton'幾乎可以在任何地方發生,但它確實有助於限制我們想要測試的範圍。 OP實際上不應該通過IMO來測試該異常。 –