原因很簡單,TestRule
計劃取代MethodRule
。 MethodRule
引入在4.7實現,並且它是一個方法的接口:
Statement apply(Statement base, FrameworkMethod method, Object target)
FrameworkMethod
(幾乎)內部JUnit類,它不應該在首位被曝光。 object
是該方法將運行的對象,例如,您可以使用反射修改測試的狀態。
TestRule
在4.9介紹,但是,是:
Statement apply(Statement base, Description description)
Description
是含有試驗的描述一個不可變POJO。修改測試狀態的方法是使用TestRule
在測試中正確封裝。這是一個完全清潔的設計。
TestWatchman(MethodRule)
和TestWatcher(TestRule)
之間的特定差異是最小的,除了TestWatcher具有更好的錯誤處理,所以這應該優先使用。兩者都有可替換的方法,例如succeeded()
,failed()
,starting()
,finished()
。
public static class WatchmanTest {
private static String watchedLog;
@Rule
public TestWatcher watchman= new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
watchedLog+= description + "\n";
}
@Override
protected void succeeded(Description description) {
watchedLog+= description + " " + "success!\n";
}
};
@Test
public void fails() {
fail();
}
@Test
public void succeeds() {
}
}
TestWatcher(TestRule)
在處理方法中處理異常。如果引發異常,則測試方法在執行測試之後而不是在執行期間失敗。
欲瞭解更多信息,請參閱TestWatcher和TestWatchman
根據選擇JUnit的4.11版本的發佈說明:「MethodRule不再是過時了。」請參閱https://github.com/KentBeck/junit/blob/master/doc/ReleaseNotes4.11.md – sversch