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"));}