从 JUnit 测试中捕获并重新抛出异常

Catch and Re-throw Exceptions from JUnit Tests

我正在寻找一种方法来捕获 JUnit 测试抛出的所有异常,然后重新抛出它们;在异常发生时向有关测试状态的错误消息添加更多详细信息。

JUnit 捕获 org.junit.runners.ParentRunner

中抛出的错误
protected final void runLeaf(Statement statement, Description description,
        RunNotifier notifier) {
    EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
    eachNotifier.fireTestStarted();
    try {
        statement.evaluate();
    } catch (AssumptionViolatedException e) {
        eachNotifier.addFailedAssumption(e);
    } catch (Throwable e) {
        eachNotifier.addFailure(e);
    } finally {
        eachNotifier.fireTestFinished();
    }
}

不幸的是,此方法是最终方法,因此无法覆盖。此外,由于正在捕获异常,因此 Thread.UncaughtExceptionHandler 之类的东西将无济于事。我能想到的唯一其他解决方案是 try/catch 块围绕每个测试,但该解决方案不是很容易维护。谁能指出我更好的解决方案?

您可以为此创建一个 TestRule

public class BetterException implements TestRule {
  public Statement apply(final Statement base, Description description) {
    return new Statement() {
      public void evaluate() {
        try {
          base.evaluate();
        } catch(Throwable t) {
          throw new YourException("more info", t);
        }
      }
    };
  }
}

public class YourTest {
  @Rule
  public final TestRule betterException = new BetterException();

  @Test
  public void test() {
    throw new RuntimeException();
  }
}