首页 文章

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

提问于
浏览
1

我正在寻找一种方法来捕获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块,但该解决方案不是很容易维护 . 有人能指出我更好的解决方案吗?

1 回答

  • 3

    你可以为此创建一个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();
      }
    }
    

相关问题