我正在对以下类运行单元测试:
public class FileClass {
public void funcB() {
try {
throw new ClassNotFoundException();
}
catch( ClassNotFoundException e ) {
}
}
}
使用模拟代码,如下所示:
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 的主体中捕获了它。
方法funcB()应该抛出异常,而不是捕获它。代码如下,测试工作正常:
public class FileClass {
public void funcB() throws ClassNotFoundException {
//try {
throw new ClassNotFoundException();
//} catch ( ClassNotFoundException e) {
//}
}
}
模拟测试:
public class TestFileClass {
@Test(expected = ClassNotFoundException.class)
public void testFuncB() throws ClassNotFoundException {
FileClass fc = Mockito.spy(new FileClass());
fc.funcB();
}
}
我认为描述测试异常的方式(@Test中的预期注释)并不是最优雅的解决方案 - 它打破了给定/何时/然后约定
最佳选择是捕获异常库
http://code.google.com/p/catch-exception/
nice中的捕获异常。但是 assertj (http://joel-costigliola.github.io/assertj/) 对异常检查有更好的支持
assertThatThrownBy(new DummyService()::someMethod)
.isInstanceOf(RuntimeException.class)
.hasMessage("Runtime exception occurred")
.hasNoCause();