前言
在寫單元測試的時候,經(jīng)常會遇到需要斷言方法需要拋出一個異常這種場景,這時,會用到Junit的異常測試功能
方式
1.使用@Test注解自帶的 expected 屬性來斷言需要拋出一個異常,如下:
@Test(expected = IllegalStateException.class)
public void testExpect() {
throw new IllegalStateException();
}
在運(yùn)行測試的時候,此方法必須拋出異常,這個測試才算通過,反之則反。
2.使用ExpectedException類來進(jìn)行打樁,我更喜歡這種方式,因為這種方式不僅能判斷出指定的異常,并且還能對消息進(jìn)行判斷,并使用一些匹配器來匹配,比較靈活,如下
先定義一個公共成員變量
@Rule
public ExpectedException thrown = ExpectedException.none();
在方法中拋出異常
@Test
public void testThrown() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("illegal");
throw new IllegalStateException("illegal");
}
還能夠使用匹配器來匹配
@Test
public void testThrownMessageMatch() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage(startsWith("illegal"));
throw new IllegalStateException("illegal xxx");
}