Skip to content

Instantly share code, notes, and snippets.

@rponte
Forked from dhemery/Applying Rules
Last active December 31, 2015 22:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rponte/8055699 to your computer and use it in GitHub Desktop.
Save rponte/8055699 to your computer and use it in GitHub Desktop.
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment