junit 测试 异常_使用JUnit规则测试预期的异常

junit 测试 异常

这篇文章展示了如何使用JUnit测试预期的异常。 让我们从我们要测试的以下类开始:

public class Person {
  private final String name;
  private final int age;

  /**
   * Creates a person with the specified name and age.
   *
   * @param name the name
   * @param age the age
   * @throws IllegalArgumentException if the age is not greater than zero
   */
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
    if (age <= 0) {
      throw new IllegalArgumentException('Invalid age:' + age);
    }
  }
}

在上面的示例中,如果人员的年龄不大于零,则Person构造函数将引发IllegalArgumentException 。 有多种方法可以测试此行为:

这是我最喜欢的方法。 ExpectedException规则允许您在测试中指定期望的异常,甚至是异常消息。 如下所示:

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class PersonTest {

  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void testExpectedException() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage(containsString('Invalid age'));
    new Person('Joe', -1);
  }
}

如下面的代码片段所示,您可以在@Test批注中指定预期的异常。 仅当test方法抛出指定类的异常时,测试才会通过。 不幸的是,您无法使用这种方法测试异常消息

@Test(expected = IllegalArgumentException.class)
public void testExpectedException2() {
  new Person('Joe', -1);
}

在引入注释和规则之前,这是旧版本的JUnit使用的“传统”方法。 将您的代码包含在try-catch子句中,并测试是否引发了异常。 如果未引发异常,请不要忘记使测试失败!

@Test
public void testExpectedException3() {
  try {
    new Person('Joe', -1);
    fail('Should have thrown an IllegalArgumentException because age is invalid!');
  } catch (IllegalArgumentException e) {
    assertThat(e.getMessage(), containsString('Invalid age'));
  }
}

参考: fahd.blog博客上的JCG合作伙伴 Fahd Shariff 用JUnit规则测试了预期的异常

翻译自: https://www.javacodegeeks.com/2013/02/testing-expected-exceptions-with-junit-rules.html

junit 测试 异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值