Junit测试预期异常

发表于:2014-9-30 13:28

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:踏雁寻花    来源:51Testing软件测试网采编

  开发人员常常使用单元测试来验证的一段儿代码的操作,很多时候单元测试可以检查抛出预期异常( expected exceptions)的代码。在Java语言中,JUnit是一套标准的单元测试方案,它提供了很多验证抛出的异常的机制。本文就探讨一下他们的优点。
  我们拿下面的代码作为例子,写一个测试,确保canVote() 方法返回true或者false, 同时你也能写一个测试用来验证这个方法抛出的IllegalArgumentException异常。
  public class Student {
  public boolean canVote(int age) {
  if (i<=0) throw new IllegalArgumentException("age should be +ve");
  if (i<18) return false;
  else return true;
  }
  }
  (Guava类库中提供了一个作参数检查的工具类--Preconditions类,也许这种方法能够更好的检查这样的参数,不过这个例子也能够检查)。
  检查抛出的异常有三种方式,它们各自都有优缺点:
  1.@Test(expected…)
  @Test注解有一个可选的参数,"expected"允许你设置一个Throwable的子类。如果你想要验证上面的canVote()方法抛出预期的异常,我们可以这样写:
  @Test(expected = IllegalArgumentException.class)
  public void canVote_throws_IllegalArgumentException_for_zero_age() {
  Student student = new Student();
  student.canVote(0);
  }
  简单明了,这个测试有一点误差,因为异常会在方法的某个位置被抛出,但不一定在特定的某行。
  2.ExpectedException
  如果要使用JUnit框架中的ExpectedException类,需要声明ExpectedException异常。
  @Rule
  public ExpectedException thrown= ExpectedException.none();
  然后你可以使用更加简单的方式验证预期的异常。
  @Test
  public void canVote_throws_IllegalArgumentException_for_zero_age() {
  Student student = new Student();
  thrown.expect(NullPointerException.class);
  student.canVote(0);
  }
  或者可以设置预期异常的属性信息。
  @Test
  public void canVote_throws_IllegalArgumentException_for_zero_age() {
  Student student = new Student();
  thrown.expect(IllegalArgumentException.class);
  thrown.expectMessage("age should be +ve");
  student.canVote(0);
  }
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号