Capture screenshot on failing SWTBot tests

September 9, 2010 | 2 min Read

Sometimes functional tests fail. If they do, I not only want to see the test and the error message, I also want a screenshot of the application in the state during the failing test.

I was astonished to find nothing in the SWTBot code or documentation that suggests how to automatically capture a screenshot when a SWTBot test fails. This is why I came up with a JUnit4 Rule that does this.

In your SWTBot test class include the field java public class MyTest { @Rule public CaptureScreenshotOnFailure screenshot = new CaptureScreenshotOnFailure(); @Test public void mytestmethod() { SWTBot bot = new SWTBot(...); // swtbot clicks and types }

So, if now mytestmethod fails, a screenshot will be put in the current directory with the name mypackage.MyTest.mytestmethod.png

This is the rule, put it somewhere where your test classes can access it:


import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement;

public class CaptureScreenshotOnFailure implements MethodRule { public final Statement apply(final Statement base, final FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (Throwable onHold) { String fileName = constructFilename(method); new SWTWorkbenchBot().captureScreenshot(fileName); throw onHold; } }

private String constructFilename(final FrameworkMethod method) { return "./" + method.getMethod().getDeclaringClass() .getCanonicalName() + "." + method.getName() + ".png"; } }; } }

I think this makes writing tests with SWTBot more comfortable. Do you see ways to improve this rule?