Junit单元测试——如何正确测试异常

普通的maven项目,导入junit4.12

这是一个有异常抛出的方法:

     /**
     * 获取某个目录下所有直接下级文件,不包括目录下的子目录的下的文件,所以不用递归获取
     * @param path 文件夹目录
     * @return path文件夹下的所有文件路径
     */
    public static List<String> getFiles(String path) {
        if(null==path){
            logger.error("传入路径不能为空!");
            throw new RuntimeException("传入路径不能为空!");
        }
        File file = new File(path);
        if(!file.exists()){
            logger.error("文件路径不存在!");
            throw new RuntimeException("文件路径不存在!");
        }
        if(!file.isDirectory()){
            logger.error("请输入文件目录!");
            throw new RuntimeException("请输入文件目录!");
        }
        //存储文件夹下的所有文件路径
        List<String> files = new ArrayList<>();
        File[] tempList = file.listFiles();
        for (File value : tempList) {
            if (value.isFile()) {
                files.add(value.toString());
            }
        }
        return files;
    }

正常场景的单元测试就用 Assert.assertEquals(期望值,返回值)

异常场景的单元测试有两种。

一种是在测试方法上的@Test加上该方法会触发的异常class。调用方法触发异常的类型和期望的异常类型相同,测试通过。如下:

但这种方法无法判断异常信息。

@Test(expected = RuntimeException.class)
public void testGetFiles(){
    FileReadUtil.getFiles(null);
}

第二种就是可以判断抛出的异常信息的:

先在类上声明ExpectedException ,测试方法中第一行写期望的异常类型,第二行写异常信息(必须完全一样),最后再调用测试的方法。注意一定要最后再调用测试方法

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testGetFiles() {//getFiles()的正常场景
        List<String> list= FileReadUtil.getFiles("src/main/data_test");
        Assert.assertEquals("src\\main\\data_test\\tcp_flow.avro",list.get(0));
    }

    @Test
    public void testGetFilesError1() {//getFiles()的异常场景1
        exception.expect(RuntimeException.class);
        exception.expectMessage("请输入文件目录!");
        FileReadUtil.getFiles("src\\main\\data_test\\tcp_flow.avro");
    }

    @Test
    public void testGetFilesError2() {//getFiles()的异常场景2
        exception.expect(RuntimeException.class);
        exception.expectMessage("文件路径不存在!");
        FileReadUtil.getFiles("src\\data");
    }

    @Test
    public void testGetFilesError3() {//getFiles()的异常场景3
        exception.expect(RuntimeException.class);
        exception.expectMessage("传入路径不能为空!");
        FileReadUtil.getFiles(null);
    }

使用第二种方法时注意不能混用第一种,也就是同时在@Test加异常期望值,这样的返回结果是不正确的。

一般使用第二种方法测试异常。

单元测试类运行:

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值