【问题标题】:Catch and Re-throw Exceptions from JUnit Tests从 JUnit 测试中捕获并重新抛出异常
【发布时间】:2015-03-30 22:45:08
【问题描述】:

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

【问题讨论】:

    标签: junit


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 1970-01-01
      • 2011-06-27
      • 2021-01-21
      • 2020-05-13
      • 2010-10-03
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多