tags:

views:

43

answers:

1

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.

+2  A: 

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.

Yishai
Thanks @Yishai. I'll check back here when I get to the real code.
Yar
Just making some notes :) `println(junit.runner.Version.id());`
Yar
Hmmm... the syntax seems to all be fine, but the `apply` method is never being run. Still figuring this thing out...
Yar
@yar, make sure your class does *not* extend TestCase, otherwise the JUnit runner will run it as a 3.8 test.
Yishai
@Yishai, thanks for all your help. It turns out I had to actually learn some stuff to make JUnit 4 work, but your code is perfect. Thanks again.
Yar