您的位置:软件测试 > 开源软件测试 > 开源单元测试工具 > junit
Java中测试异常的多种方式
作者:网络转载 发布时间:[ 2014/7/28 16:22:47 ] 推荐标签:开源单元测试

  这是容易想到的一种方式,但是太?嗦。

  JUnit annotation方式

  JUnit中提供了一个expected的annotation来检查异常。

    @Test(expected = IllegalArgumentException.class)
    public void shouldGetExceptionWhenAgeLessThan0() {
        Person person = new Person();
        person.setAge(-1);

    }
  这种方式看起来要简洁多了,但是无法检查异常中的消息。

  ExpectedException rule

  JUnit7以后提供了一个叫做ExpectedException的Rule来实现对异常的测试。

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

    @Test
    public void shouldGetExceptionWhenAgeLessThan0() {

        Person person = new Person();
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage(containsString("age is invalid"));
        person.setAge(-1);

    }
  这种方式既可以检查异常类型,也可以验证异常中的消息。

  使用catch-exception库

  有个catch-exception库也可以实现对异常的测试。

  首先引用该库。

  pom.xml


        <dependency>
            <groupId>com.googlecode.catch-exception</groupId>
            <artifactId>catch-exception</artifactId>
            <version>1.2.0</version>
            <scope>test</scope> <!-- test scope to use it only in tests -->
        </dependency>

上一页1234下一页
软件测试工具 | 联系我们 | 投诉建议 | 诚聘英才 | 申请使用列表 | 网站地图
沪ICP备07036474 2003-2017 版权所有 上海泽众软件科技有限公司 Shanghai ZeZhong Software Co.,Ltd