您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
Junit中的異常測試
作者:pengshuangbao 發(fā)布時(shí)間:[ 2017/2/14 11:19:08 ] 推薦標(biāo)簽:單元測試 Junit

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

軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd