2013-02-22 33 views
1

我最近在深入挖掘JUnit-4.11的源代碼,讓我困惑的是看似多餘的Protectable接口。聲明如下:JUnit源代碼中Proctectable接口的含義是什麼?

public interface Protectable { 
    public abstract void protect() throws Throwable; 
} 

TestResult類,有一個void run(final TestCase test)方法,其中,如下一個匿名Protectable實例實現:

protected void run(final TestCase test) { 
    startTest(test); 
    Protectable p = new Protectable() { 
     public void protect() throws Throwable { 
      test.runBare(); 
     } 
    }; 
    runProtected(test, p); 

    endTest(test); 
} 

runProtected方法如下:

public void runProtected(final Test test, Protectable p) { 
    try { 
     p.protect(); 
    } catch (AssertionFailedError e) { 
     addFailure(test, e); 
    } catch (ThreadDeath e) { // don't catch ThreadDeath by accident 
     throw e; 
    } catch (Throwable e) { 
     addError(test, e); 
    } 
} 

正如我們所看到的,runProtected所做的只是執行test.runBare();,所以我對Protectable接口的存在有什麼意義?爲什麼我們不能像以下編寫代碼?

protected void run(final TestCase test) { 
    startTest(test); 
    test.runBare(); 
    endTest(test); 
} 

回答

2

要回答你的最後一個問題首先,你不能使用

protected void run(final TestCase test) { 
    startTest(test); 
    test.runBare(); 
    endTest(test); 
} 

因爲它不會做你想做的。 JUnit使用異常來管理斷言,具體爲AssertionFailedError。因此,當兩個值不相等時,Assert.assertEquals()將引發一個AssertionFailedError。因此,在上述方法中,如果斷言失敗,則不會調用endTest(test),這意味着正確的事件(測試的失敗/錯誤)不會被觸發,並且tearDown()將不會被執行。

Protectable接口在那裏爲跑步者提供了一個更通用的界面,因此您不必將TestCase交給該方法,以允許執行不同的操作。

另外,這是包junit.framework.*,它是JUnit 3的一部分.JUnit 4是它所在的位置,如果您想了解,請在org.junit.*包中查看更多內容。

0

似乎來處理特定的方式拋出的異常: 呼叫addFailure的斷言異常(測試失敗),addError其他異常(你的測試不能很好地編碼)

相關問題