如何惯用JUnit4来测试某些代码引发异常?
虽然我当然可以做这样的事情:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
我记得在这种情况下,有一个批注或一个Assert.xyz或一些不那么杂乱无章的东西 ,更是JUnit的精髓。
#1楼
我在这里尝试了许多方法,但是它们要么很复杂,要么不完全符合我的要求。 实际上,可以很简单地编写一个辅助方法:
public class ExceptionAssertions {
public static void assertException(BlastContainer blastContainer ) {
boolean caughtException = false;
try {
blastContainer.test();
} catch( Exception e ) {
caughtException = true;
}
if( !caughtException ) {
throw new AssertionFailedError("exception expected to be thrown, but was not");
}
}
public static interface BlastContainer {
public void test() throws Exception;
}
}
像这样使用它:
assertException(new BlastContainer() {
@Override
public void test() throws Exception {
doSomethingThatShouldExceptHere();
}
});
零依赖性:无需模拟,无需powermock; 并且在期末课程上也能正常工作。
#2楼
怎么做:捕获一个非常普通的异常,确保它使它脱离catch块,然后断言该异常的类就是您期望的异常。 如果a)异常的类型错误(例如,如果您改为使用Null指针),并且b)从未引发异常,则该断言将失败。
public void testFooThrowsIndexOutOfBoundsException() {
Throwable e = null;
try {
foo.doStuff();
} catch (Throwable ex) {
e = ex;
}
assertTrue(e instanceof IndexOutOfBoundsException);
}
#3楼
JUnit对此具有内置支持,并带有“ expected”属性
#4楼
JUnit 4
为此提供支持:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
参考:
#5楼
使用预期的异常时要小心,因为它仅断言该方法引发了该异常,而不是测试中的特定代码行 。
我倾向于将其用于测试参数验证,因为此类方法通常非常简单,但最好将更复杂的测试用于:
try {
methodThatShouldThrow();
fail( "My method didn't throw when I expected it to" );
} catch (MyException expectedException) {
}
运用判断。
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3137574