JUnit annotation方式
JUnit中提供了一個expected的annotation來檢查異常。
	    @Test(expected = IllegalArgumentException.class)
	    public void shouldGetExceptionWhenAgeLessThan0() {
	        Person person = new Person();
	        person.setAge(-1);
	    }
	  這種方式看起來要簡潔多了,但是無法檢查異常中的消息。
ExpectedException rule
JUnit7以后提供了一個叫做ExpectedException的Rule來實(shí)現(xiàn)對異常的測試。
	    @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);
	    }
	  這種方式既可以檢查異常類型,也可以驗(yàn)證異常中的消息。
使用catch-exception庫
有個catch-exception庫也可以實(shí)現(xiàn)對異常的測試。
首先引用該庫。
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>