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);  
        }  
    } 
  • 相关阅读:
    nodejs 不支持 typescript (...paramName:any[])剩余参数。变相支持方式。
    centos7安装nodejs
    .Net Core Linux centos7行—jenkins linux 构建.net core web app
    asp.net core 编译mvc,routing,security源代码进行本地调试
    发现一个很N且免费的html5拓扑图 关系图 生成组件
    Quill编辑器介绍及扩展
    vs2017 rc 离线安装包制作
    单体架构风格
    GlusterFS 安装 on centos7
    Expect 安装 on centos7
  • 原文地址:https://www.cnblogs.com/miniren/p/4638511.html
Copyright © 2011-2022 走看看