单元测试系列二:单元测试如何测试异常与超时

吃可爱长大的小学妹 提交于 2019-11-27 19:21:42

一、 测试异常
1. 使用@test的expected属性测试异常

    // 第一种方式, 使用expected属性
    @Test(expected = FileNotFoundException.class)
    public void usingExpected() throws FileNotFoundException {
        // 不会抛出FileNotFoundException的代码写在上面

        new FileInputStream("不存在的文件路径");
    }
2. 使用try/catch,fail的方式测试异常
    // 第二种方式, 使用try/catch和fail方法
    @Test
    public void usingTryCatchAndFail() {
        // 其他代码
        try {
            new FileInputStream("不存在的文件路径");
            fail("前面的代码已经抛出FileNotFoundException!");
        } catch (FileNotFoundException e) {
            assertTrue(e.getMessage().contains("不存在的文件路径"));
        }
    }
3. 使用@Rule,expectedException的方式测试异常
    // 第三种方式, 使用ExpectedException规则
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void shouldTestExceptionMessage() throws FileNotFoundException {
        thrown.expect(FileNotFoundException.class);
        thrown.expectMessage("不存在的文件路径");
        thrown.expectMessage("存在");
        thrown.expectMessage("文件路径");
        new FileInputStream("不存在的文件路径");
    }

二、 测试超时
1. 使用@test的timeout属性测试超时

    // 第一种方式,使用timeout属性
    @Test(timeout=1000)
    public void timeoutIn1Seconds(){
        System.out.println("一秒钟超时");
        while(true){}
    }
2. 使用@rule,timeout的方式测试超时
    // 第二种方式,使用Timeout规则
    @Rule
    public Timeout globalTimeout=new Timeout(5000);
    //Timeout.seconds(5);//这个 <code>seconds</code>方法只在JUnit 4.12版本之后才有效

    @Test
    public void timeoutIn5Seonds(){
        System.out.println("五秒钟超时");
        while(true){}
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!