Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 690|回复: 0

Java中测试异常的多种方式

[复制链接]
  • TA的每日心情
    奋斗
    2024-9-22 15:19
  • 签到天数: 795 天

    [LV.10]以坛为家III

    2050

    主题

    2108

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    724084
    发表于 2021-7-15 11:54:50 | 显示全部楼层 |阅读模式

    使用JUnit来测试Java代码中的异常有很多种方式,你知道几种?

    给定这样一个class。

    Person.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    
    public class Person {   private String name;  private int age;   public String getName() {  return name;  }   public void setName(String name) {  this.name = name;  }   public int getAge() {  return age;  }   public void setAge(int age) {   if (age < 0 ) {  throw new IllegalArgumentException("age is invalid");  }  this.age = age;  } } 

    我们来测试setAge方法。

    Try-catch 方式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
     @Test  public void shouldGetExceptionWhenAgeLessThan0() {  Person person = new Person();  try {  person.setAge(-1);  fail("should get IllegalArgumentException");  } catch (IllegalArgumentException ex) {  assertThat(ex.getMessage(),containsString("age is invalid"));  }   } 

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

    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> 

    然后这样书写测试。

    1
    2
    3
    4
    5
    6
    7
    8
    
     @Test  public void shouldGetExceptionWhenAgeLessThan0() {  Person person = new Person();  catchException(person).setAge(-1);  assertThat(caughtException(),instanceOf(IllegalArgumentException.class));  assertThat(caughtException().getMessage(), containsString("age is invalid"));   } 

    这样的好处是可以精准的验证异常是被测方法抛出来的,而不是其它方法抛出来的。

    catch-exception库还提供了多种API来进行测试。

    先加载fest-assertion库。

    1
    2
    3
    4
    5
    
     <dependency>  <groupId>org.easytesting</groupId>  <artifactId>fest-assert-core</artifactId>  <version>2.0M10</version>  </dependency> 

    然后可以书写BDD风格的测试。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
     @Test  public void shouldGetExceptionWhenAgeLessThan0() {  // given  Person person = new Person();   // when  when(person).setAge(-1);   // then  then(caughtException())  .isInstanceOf(IllegalArgumentException.class)  .hasMessage("age is invalid")  .hasNoCause();  } 

    如果喜欢Hamcrest风格的验证风格的话,catch-exception也提供了相应的Matcher API。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
     @Test  public void shouldGetExceptionWhenAgeLessThan0() {  // given  Person person = new Person();   // when  when(person).setAge(-1);   // then  assertThat(caughtException(), allOf(  instanceOf(IllegalArgumentException.class)  , hasMessage("age is invalid")  ,hasNoCause()));  } 

    第一种最土鳖,第二种最简洁,第四种最靠谱。

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-10-6 03:45 , Processed in 0.064048 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表