Skip to content

Instantly share code, notes, and snippets.

@dhemery
Created December 14, 2010 23:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhemery/741341 to your computer and use it in GitHub Desktop.
Save dhemery/741341 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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