Junit中的異常測試


前言

     在寫單元測試的時候,經常會遇到需要斷言方法需要拋出一個異常這種場景,這時,就會用到Junit的異常測試功能

方式

     1.使用@Test注解自帶的 expected 屬性來斷言需要拋出一個異常,如下:

     @Test(expected = IllegalStateException.class)

     public void testExpect() {

           throw new IllegalStateException();

     }

     在運行測試的時候,此方法必須拋出異常,這個測試才算通過,反之則反。

     2.使用ExpectedException類來進行打樁,我更喜歡這種方式,因為這種方式不僅能判斷出指定的異常,並且還能對消息進行判斷,並使用一些匹配器來匹配,比較靈活,如下

      先定義一個公共成員變量 

     @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");

     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM