Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why have JUnit MethodRule and TestWatchman have been deprecated?

org.junit.rules.MethodRule and org.junit.rules.TestWatchman have been deprecated.

one interesting note was at: https://github.com/junit-team/junit/pull/519 , in part: "Many developers are legitimate reasons to stick with MethodRule and the JUnit team has no plans to remove support for MethodRule..."

http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatchman.html documents: "Deprecated. MethodRule is deprecated. Use TestWatcher implements TestRule instead." and provides some example code.

What is the reasoning behind marking these deprecated? What is the tradeoff between TestWatcher and the deprecated TestWachman? Do you have a good link for a synopsis or overview on this specific topic?

like image 377
FrankBoller Avatar asked Oct 18 '12 23:10

FrankBoller


1 Answers

The reason is simple, TestRule was planned to replace MethodRule. MethodRule was introduced implemented in 4.7, and it is an interface with one method:

Statement apply(Statement base, FrameworkMethod method, Object target)

FrameworkMethod is (almost) an internal JUnit class, which shouldn't have been exposed in the first place. object is the object on which the method will be run, so for example, you can modify state of the test using reflection.

TestRule was introduced in 4.9, however, is:

Statement apply(Statement base, Description description)

Description is a immutable POJO containing the description of the test. The way to modify state within a test is to encapsulate correctly within the test using a TestRule. It's an altogether cleaner design.

The specific difference between TestWatchman(MethodRule) and TestWatcher(TestRule) is minimal, except that TestWatcher has better error handling, so this should be used in preference. Both have overridable methods such as 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) handles exceptions in the overidden methods. If exceptions are thrown, then the test method fails after execution of the test, rather than during.

For more information, see TestWatcher and TestWatchman

like image 195
Matthew Farwell Avatar answered Oct 01 '22 22:10

Matthew Farwell