2015-03-30 72 views
0

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

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

该解决方案非常完美,非常感谢。 – ntin 2015-03-31 15:24:37