Usage and Idioms——Exception testing

   可预期的异常测试

   一般如何判定程序抛出的异常正是你所预期的呢?在常规环境中,保证程序正常跑完很重要;但是在异常环境中,确保程序能够按照预期的来执行,更加重要。比如说:

new ArrayList<Object>().get(0);
这段代码应该抛出的异常信息为:IndexOutOfBoundsException

@Test注释有一个可选参数expected ,可将异常信息的子类赋值给该参数。如果我们想判定ArrayList 是否抛出了预期的异常,可以这样写:
@Test(expected = IndexOutOfBoundsException.class) public void empty() { new ArrayList<Object>().get(0); }


请慎用expected参数,如果上述方法中任何代码抛出IndexOutOfBoundsException 信息,这个测试都会通过。对于比较长的测试程序,推荐用 ExpectedException 方法。

深层次的异常测试
ExpectedException Rule
:允许在程序中标识出预期的异常,同时显示异常相关的信息。代码如下:

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
    List<Object> list = new ArrayList<Object>();

    thrown.expect(IndexOutOfBoundsException.class);
    thrown.expectMessage("Index: 0, Size: 0");
    list.get(0); // execution will never get past this line
}


其中,expectMessage 允许加入Matchers,这使测试方法更加灵活,比如说:
thrown.expectMessage(Matchers.containsString("Size: 0"));

而且,Matchers可以用来检测异常,尤其是想验证内置状态时非常有用。

 





 

 

原文地址:https://www.cnblogs.com/insist8089/p/6394879.html