publicclassPerson{privateStringname;privateintage;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){if(age<0){thrownewIllegalArgumentException("age is invalid");}this.age=age;}}
我们来测试setAge方法。
Try-catch 方式
1234567891011
@TestpublicvoidshouldGetExceptionWhenAgeLessThan0(){Personperson=newPerson();try{person.setAge(-1);fail("should get IllegalArgumentException");}catch(IllegalArgumentExceptionex){assertThat(ex.getMessage(),containsString("age is invalid"));}}
@RulepublicExpectedExceptionexception=ExpectedException.none();@TestpublicvoidshouldGetExceptionWhenAgeLessThan0(){Personperson=newPerson();exception.expect(IllegalArgumentException.class);exception.expectMessage(containsString("age is invalid"));person.setAge(-1);}
这种方式既可以检查异常类型,也可以验证异常中的消息。
使用catch-exception库
有个catch-exception库也可以实现对异常的测试。
首先引用该库。
pom.xml
123456
<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>
然后这样书写测试。
12345678
@TestpublicvoidshouldGetExceptionWhenAgeLessThan0(){Personperson=newPerson();catchException(person).setAge(-1);assertThat(caughtException(),instanceOf(IllegalArgumentException.class));assertThat(caughtException().getMessage(),containsString("age is invalid"));}