java测试程序无异常_Java中测试异常的多种方式

学习Java的同学注意了!!!

学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:589809992我们一起学Java!

使用JUnit来测试Java代码中的异常有很多种方式,你知道几种?

给定这样一个class。

Person.java

public class Person {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {if (age < 0 ) {throw new IllegalArgumentException("age is invalid");}this.age = age;}}

我们来测试setAge方法。

Try-catch 方式

@Testpublic void shouldGetExceptionWhenAgeLessThan0() {Person person = new Person();try {person.setAge(-1);fail("should get IllegalArgumentException");} catch (IllegalArgumentException ex) {assertThat(ex.getMessage(),containsString("age is invalid"));}}

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

JUnit annotation方式

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

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

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

ExpectedException rule

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

@Rulepublic ExpectedException exception = ExpectedException.none();@Testpublic 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

com.googlecode.catch-exceptioncatch-exception1.2.0test

然后这样书写测试。

@Testpublic void shouldGetExceptionWhenAgeLessThan0() {Person person = new Person();catchException(person).setAge(-1);assertThat(caughtException(),instanceOf(IllegalArgumentException.class));assertThat(caughtException().getMessage(), containsString("age is invalid"));}

这样的好处是可以精准的验证异常是被测方法抛出来的,而不是其它方法抛出来的。

catch-exception库还提供了多种API来进行测试。

先加载fest-assertion库。

org.easytestingfest-assert-core2.0M10

然后可以书写BDD风格的测试。

@Testpublic void shouldGetExceptionWhenAgeLessThan0() {// givenPerson person = new Person();// whenwhen(person).setAge(-1);// thenthen(caughtException()).isInstanceOf(IllegalArgumentException.class).hasMessage("age is invalid").hasNoCause();}

如果喜欢Hamcrest风格的验证风格的话,catch-exception也提供了相应的Matcher API。

@Testpublic void shouldGetExceptionWhenAgeLessThan0() {// givenPerson person = new Person();// whenwhen(person).setAge(-1);// thenassertThat(caughtException(), allOf(instanceOf(IllegalArgumentException.class), hasMessage("age is invalid"),hasNoCause()));}

第一种最土鳖,第二种最简洁,第四种最靠谱。

学习Java的同学注意了!!!

学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:589809992我们一起学Java!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值