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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With