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

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

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