Create a gist now

Instantly share code, notes, and snippets.

How to write and apply JUnit Rules.
public class MyTest {
@Rule
public MethodRule screenshot = new ScreenshotOnFailureRule();
@Test
public void myTest() { ... }
...
}
public class ScreenshotOnFailureRule implements MethodRule {
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
if(allowsScreenshot(method)) {
String className = method.getMethod().getDeclaringClass().getSimpleName();
String methodName = method.getName();
return new ScreenshotOnFailureStatement(base, className, methodName);
}
else {
return base;
}
}
private boolean allowsScreenshot(FrameworkMethod method) {
return method.getAnnotation(NoScreenshot.class) == null;
}
}
public class ScreenshotOnFailureRule implements MethodRule {
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
String className = method.getMethod().getDeclaringClass().getSimpleName();
String methodName = method.getName();
return new ScreenshotOnFailureStatement(base, className, methodName);
}
}
public class ScreenshotOnFailureStatement extends Statement {
private final Statement base;
private final String className;
private final String methodName;
public ScreenshotOnFailureStatement(Statement base, String className, String methodName) {
this.base = base;
this.className = className;
this.methodName = methodName;
}
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
}
catch(Throwable e) {
MyScreenshooter.takeScreenshot(className, methodName);
throw e;
}
}
}
@dhemery
Owner
dhemery commented Dec 15, 2010

Note: These examples are for JUnit 4.8.2. In JUnit 4.9, MethodRule will be replaced by TestRule, which has a slightly different interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment