Il motivo è semplice, TestRule
è stato pianificato per sostituire MethodRule
. MethodRule
è stato introdotto implementato in 4.7, ed è un'interfaccia con un metodo:
Statement apply(Statement base, FrameworkMethod method, Object target)
FrameworkMethod
è (quasi) una classe JUnit interna, che non avrebbe dovuto essere esposto, in primo luogo. object
è l'oggetto su cui verrà eseguito il metodo, quindi, ad esempio, è possibile modificare lo stato del test mediante la riflessione.
TestRule
stato introdotto in 4,9, tuttavia, è:
Statement apply(Statement base, Description description)
Description
è un POJO immutabile contenente la descrizione del test. Il modo per modificare lo stato di un test è incapsulare correttamente all'interno del test utilizzando TestRule
. È un design completamente più pulito.
La differenza specifica tra TestWatchman(MethodRule)
e TestWatcher(TestRule)
è minima, tranne che TestWatcher ha una migliore gestione degli errori, pertanto è preferibile utilizzarlo. Entrambi hanno metodi sovrascrivibili come 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)
gestisce le eccezioni nei metodi overidden. Se vengono lanciate eccezioni, il metodo di prova fallisce dopo l'esecuzione del test, piuttosto che durante.
Per ulteriori informazioni, vedere TestWatcher e TestWatchman
Secondo le note di rilascio per la versione 4.11 di JUnit: "MethodRule non è più deprecato" Vedere https://github.com/KentBeck/junit/blob/master/doc/ReleaseNotes4.11.md – sversch