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);  
        }  
    } 
  • 相关阅读:
    idea高效实用快捷键【待补充】
    前台sessionStorage存取对象注意事项
    SpringBoot2.0 整合 JWT 框架后台生成token
    vue暗含玄机的v-for指令
    【串线篇】spring boot自定义starter
    【串线篇】spring boot启动配置原理
    【串线篇】spring boot整合SpringData JPA
    docker安装MySQL5.7示例!!坑,ERROR 1045 (28000): Access denied for user
    docker常用命令及操作
    docker简介及安装
  • 原文地址:https://www.cnblogs.com/miniren/p/4638511.html
Copyright © 2011-2022 走看看