zoukankan      html  css  js  c++  java
  • 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);  
        }  
    } 
  • 相关阅读:
    MySQL Sandbox安装使用
    主从复制延时判断
    Carthage
    QCon 2015 阅读笔记
    QCon 2015 阅读笔记
    Scrum&Kanban在移动开发团队的实践 (一)
    移动开发-第三方聊天服务
    开通博客
    spark的若干问题
    hadoop2.2.0安装需要注意的事情
  • 原文地址:https://www.cnblogs.com/miniren/p/4638511.html
Copyright © 2011-2022 走看看