• <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>
  • Java中測試異常的多種方式(2)

    發表于:2014-04-14來源:博客園作者:黃博文點擊數: 標簽:軟件測試
    這是最容易想到的一種方式,但是太啰嗦。 JUnit annotation方式 JUnit中提供了一個expected的annotation來檢查異常。 1 2 3 4 5 6 @Test ( expected = IllegalArgumentException

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

      JUnit annotation方式

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

    1
    2
    3
    4
    5
    6
    
        @Test(expected = IllegalArgumentException.class)
        public void shouldGetExceptionWhenAgeLessThan0() {
            Person person = new Person();
            person.setAge(-1);
    
        }
    

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

      ExpectedException rule

      JUnit7以后提供了一個叫做ExpectedException的Rule來實現對異常的測試。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
        @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);
    
        }
    

      這種方式既可以檢查異常類型,也可以驗證異常中的消息。

      使用catch-exception庫

      有個catch-exception庫也可以實現對異常的測試。

      首先引用該庫。

      pom.xml

    1
    2
    3
    4
    5
    6
    
            <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>
    

    原文轉自:http://www.cnblogs.com/huang0925/p/3663074.html

    老湿亚洲永久精品ww47香蕉图片_日韩欧美中文字幕北美法律_国产AV永久无码天堂影院_久久婷婷综合色丁香五月

  • <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>