Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping JUnit Tests (in Eclipse)

Tags:

java

junit

groovy

All of my tests for my Groovy code look like this

public void testButtons() {
    try {
         page.getButtons();
    } catch (Exception e) {
         throw org.codehaus.groovy.runtime.StackTraceUtils.sanitize(e);     
    }
}

because I need to sanitize any possible StackTrace that appears (otherwise it's very hard to read since it's got all the Groovy meta-code). Is there any way to specify that all JUnit tests get wrapped in particular way (like an error handler)?

Note: I am running these in Eclipse, but if there's a way to do this in IntelliJ or Netbeans, that would be good to know.

like image 260
Dan Rosenstark Avatar asked May 04 '10 22:05

Dan Rosenstark


1 Answers

Yes, use a Rule. Basically you have to have a class which implements the MethodRule interface that handles the exception handling in the apply method by substituting its own Statement implementation that has the try/catch in it.

To use a rule you define a field in the test class like so:

  @Rule public MethodRule exceptionCleanser = new ExceptionCleanser();

A first cut implementation would probably look something like this:

  public class ExceptionCleanser implements MethodRule {

      public Statement apply(final Statement base, FrameworkMethod method, Object target) {
          return new Statement() {
               public void evaluate() throws Throwable {
                 try {
                    base.evaluate();
                 } catch (Exception e) {
                       throw org.codehaus.groovy.runtime.StackTraceUtils.sanitize(e);     
                 }
               }
          };
      }
  }

The above is totally untested, but you should be able to get the idea. The @Rule annotation was introduced in JUnit 4.7, so you may need to update to use it.

like image 101
Yishai Avatar answered Oct 14 '22 17:10

Yishai