Blog

Making screenshots from Selenium with JUnit @Rule’s

30 Mar, 2010
Xebia Background Header Wave

When running Selenium tests from JUnit it’s very useful to be able to capture screenshots when something fails. Especially when you run it in a Continuous Integration environment which you aren’t monitoring. A screenshot combined with the stacktrace makes identifying and fixing the error easier. When you combine this with a JUnit @Rule you can make it transparant and use it for every testcase
Implementing the @Rule
For implementing rules you need to implement the MethodRule interface and implement the apply method. The base.evaluate method invokes the unittest. The screenshot is made in case of any exception which is re-thrown as a RuntimeException so that your testcase will fail. This class extends the SeleneseTestBase which helps you writing selenium unit tests. Capturing screenshots is a feature of selenium and is very easy. You might want to store the file differently, but that should be easy.
[code lang="java"]
public class CapturingSelenium extends SeleneseTestBase implements MethodRule {
@Override
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
setUp("xebia.com / blog : 8080/", "*firefox");
base.evaluate();
}
catch (Exception e) {
selenium.captureEntirePageScreenshot("/tmp/selenium-error-" + new UUID().toString() + ".PNG", "");
throw new RuntimeException(e);
}
}
};
}
[/code]
That’s it. Now you can just use the CapturingSelenium class and annotate it with @Rule. When any test fails with an exception the rule catches it and captures a screenshot of the browser at the time of the exception. Here’s a basic example:
Usage:
[code lang="java"]
public class SeleniumTest {
@Rule
private CapturingSelenium selenium = new CapturingSelenium();
@Test(expected=RuntimeException.class)
public void shouldCaptureScreenshotWhenFailing() throws Exception {
selenium.open("https://xebia.com/blog/myapp/home");
selenium.click("some-button-which-is-not-there");
//…
}
}
[/code]

Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts