2015-03-30 94 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