Exception testing

怎样去验证代码是否抛出我们期望的异常呢?虽然在代码正常结束时候验证很重要,但是在异常的情况下确保代码如我们希望的运行也很重要。比如说:

new ArrayList<Object>().get(0);

这句代码会抛出一个IndexOutOfBoundsException异常。有三种方法来验证ArrayList是否抛出了正确的异常。

1. @Test 里面加上一个参数"expected"。(参见test01)

谨慎使用expected参数。方法里的任意代码抛出IndexOutOfBoundsException异常都会导致该测试pass。复杂的测试建议使用 ExpectedException 规则。

2.Try/Catch(参见test02)

方法1仅仅适用于简单的例子,它有它的局限性。比如说,我们不能测试异常的信息返回值,或者异常抛出之后某个域对象的状态。对于这种需求我们可以采用JUnit 3.x流行的 try/catch 来实现。

3.ExpectedException 规则(参见test03)

该规则不仅可以测试抛出的异常,还可以测试期望的异常信息。

 

import static org.junit.Assert.*;  
import static org.hamcrest.CoreMatchers.*;  
import java.util.ArrayList;  
import java.util.List;  
import org.junit.Rule;  
import org.junit.Test;  
import org.junit.rules.ExpectedException;  
  
public class ExceptionTest {  
      
    @Test(expected=IndexOutOfBoundsException.class)  
    public void test01(){  
        new ArrayList<Object>().get(0);  
    }  
      
    @Test()  
    public void test02(){  
        try{  
            new ArrayList<Object>().get(0);  
            fail("Expected an IndexOutOfBoundsException to be thrown");  
        }catch(IndexOutOfBoundsException e){  
            assertThat(e.getMessage(),is("Index: 0, Size: 0"));  
        }  
    }  
      
    @Rule  
    public ExpectedException thrown=ExpectedException.none();  
      
    @Test  
    public void test03() throws IndexOutOfBoundsException{  
        List<Object> list=new ArrayList<Object>();  
        thrown.expect(IndexOutOfBoundsException.class);  
        thrown.expectMessage("Index: 0, Size: 0");  
        list.get(0);  
    }  
} 

 

posted @ 2015-07-11 13:48  微微微笑  阅读(384)  评论(0编辑  收藏  举报