我正在对以下课程进行单元测试:
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
进行任何测试?
答案 0 :(得分:7)
funcB没有抛出异常,因为你是在funcB的主体内捕获它。
答案 1 :(得分:1)
方法funcB()应抛出异常,而不是捕获它。代码低于测试工作:
public class FileClass {
public void funcB() throws ClassNotFoundException {
//try {
throw new ClassNotFoundException();
//} catch ( ClassNotFoundException e) {
//}
}
}
Mockito测试:
public class TestFileClass {
@Test(expected = ClassNotFoundException.class)
public void testFuncB() throws ClassNotFoundException {
FileClass fc = Mockito.spy(new FileClass());
fc.funcB();
}
}
答案 2 :(得分:1)
我认为描述测试异常的方法(@Test中的预期注释)并不是最优雅的解决方案 - 它会给出/当/然后约定
最佳选择是catch-exception库
答案 3 :(得分:0)
很好的抓住异常。但是assertj(http://joel-costigliola.github.io/assertj/)对异常检查有更好的支持
assertThatThrownBy(new DummyService()::someMethod)
.isInstanceOf(RuntimeException.class)
.hasMessage("Runtime exception occurred")
.hasNoCause();