我已经用@Test注释编写了一些JUnit测试。如果我的测试方法抛出一个检查过的异常,并且如果我想断言该消息与异常一起,是否有一种方法可以使用JUnit @Test注释来做到这一点?AFAIK, JUnit 4.7不提供这个功能,但是将来的版本会提供吗?我知道在。net中你可以断言消息和异常类。在Java世界中寻找类似的特性。

这就是我想要的:

@Test (expected = RuntimeException.class, message = "Employee ID is null")
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() {}

当前回答

实际上,最好的用法是try/catch。为什么?因为您可以控制异常发生的位置。

想想这个例子:

@Test (expected = RuntimeException.class)
public void someTest() {
   // test preparation
   // actual test
}

如果有一天代码被修改,测试准备将抛出RuntimeException,该怎么办?在这种情况下,实际的测试甚至没有测试,即使它没有抛出任何异常,测试也会通过。

这就是为什么使用try/catch比依赖注释要好得多的原因。

其他回答

如果使用@Rule,则异常集将应用于test类中的所有测试方法。

导入catch-exception库,并使用它。它比ExpectedException规则或try-catch规则干净得多。

他们文档中的例子:

import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;

// given: an empty list
List myList = new ArrayList();

// when: we try to get the first element of the list
catchException(myList).get(1);

// then: we expect an IndexOutOfBoundsException with message "Index: 1, Size: 0"
assertThat(caughtException(),
  allOf(
    instanceOf(IndexOutOfBoundsException.class),
    hasMessage("Index: 1, Size: 0"),
    hasNoCause()
  )
);
@Test (expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "This is not allowed")
public void testInvalidValidation() throws Exception{
     //test code
}

我喜欢@Rule的答案。但是,如果出于某种原因您不想使用规则。还有第三种选择。

@Test (expected = RuntimeException.class)
public void myTestMethod()
{
   try
   {
      //Run exception throwing operation here
   }
   catch(RuntimeException re)
   {
      String message = "Employee ID is null";
      assertEquals(message, re.getMessage());
      throw re;
    }
    fail("Employee Id Null exception did not throw!");
  }

你可以使用@Rule注释和ExpectedException,就像这样:

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

@Test
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
    expectedEx.expect(RuntimeException.class);
    expectedEx.expectMessage("Employee ID is null");

    // do something that should throw the exception...
    System.out.println("=======Starting Exception process=======");
    throw new NullPointerException("Employee ID is null");
}

注意,ExpectedException文档中的例子(目前)是错误的——没有公共构造函数,所以你必须使用ExpectedException.none()。