您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源單元測(cè)試工具 > junit
Java中測(cè)試異常的多種方式
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2014/7/28 16:22:47 ] 推薦標(biāo)簽:開源單元測(cè)試

  這是容易想到的一種方式,但是太?嗦。

  JUnit annotation方式

  JUnit中提供了一個(gè)expected的annotation來檢查異常。

    @Test(expected = IllegalArgumentException.class)
    public void shouldGetExceptionWhenAgeLessThan0() {
        Person person = new Person();
        person.setAge(-1);

    }
  這種方式看起來要簡(jiǎn)潔多了,但是無法檢查異常中的消息。

  ExpectedException rule

  JUnit7以后提供了一個(gè)叫做ExpectedException的Rule來實(shí)現(xiàn)對(duì)異常的測(cè)試。

    @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庫(kù)

  有個(gè)catch-exception庫(kù)也可以實(shí)現(xiàn)對(duì)異常的測(cè)試。

  首先引用該庫(kù)。

  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>

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