首页 > 其他 > 详细

Junit 测试exception

时间:2016-06-23 16:00:24      阅读:183      评论:0      收藏:0      [点我收藏+]

有两种方法:

一、使用ExpectedException

仅在junit4.7以上支持。不仅可以测试捕获到某异常,也可以测试异常message。

使用例子如下:

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

    @Test
    public void shouldThrowExceptionWhenSumGivenOneNegativeNumber() throws Exception {
        exception.expect(Exception.class);
        exception.expectMessage(containsString("negatives not allowed"));
        exception.expectMessage(containsString("-1"));
        StringCalculator.calculate("-1,1");
    }

public static int calculate(String numbers) throws Exception {
       throw new Exception("negatives not allowed: -1");
    }

注意事项:

1. ExpectedException 必须是public

 

二、使用annotation

这个只能测存在异常,测不了异常message

使用方法:

@Test(expected = Exception.class)
    public void testException() throws Exception {
        StringCalculator.calculate("-1,-1");
    }

 

Junit 测试exception

原文:http://www.cnblogs.com/hf-cherish/p/5610892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!