in webdriver java screenshot ~ read.

How to capture screenshots on WebDriver failure

Let's say that you have your nice WebDriver project that does some tests already. Now, you're moving this tests to Jenkins, so they would run all the time. But you face another problem - you get some errors, exceptions but it's not always obvious what went wrong and why button could not be clicked or something similar. Here comes screenshots for help. As it's said - "One picture can be more valueble then 100 words". So, where do we start? Most probably you already have this code in your project :

WebDriver driver;

    @Before
    public void setUp() {
        driver = new FirefoxDriver();
    }

You will need to change it to next :

WebDriver driver;

    @Before
    public void setUp() {
        WebDriverEventListener eventListener = new MyEventListener();
        driver = new EventFiringWebDriver(new FirefoxDriver()).register(eventListener);
    }

This great, but you will notice now that you're IDE is complaining about missing MyEventListener class. So, let's create it !

public class MyEventListener implements WebDriverEventListener {
    // You will need to implement all methods, but it's fine
    // just leave them empty. The only method we care is 
    // onException - this method is responsible on 
    // Webdriver actions when it throws some exceptions
    // Don't forget - it acts only on WebDriver exceptions
    // Assert exceptions will be ignored

    public void onException(Throwable arg0, WebDriver arg1) {
        String filename = generateRandomFilename(arg0);
        createScreenCaptureJPEG(filename);
    }
}

The rest is simple - i have several methods which create folder for screen shots and put screenshot in it. Main folder is saved in root of the project and i usually add it to .gitignore. All screen shots are getting stored in separate folder - one folder per each day, so it will be easier to find needed screen shots on CI machine. You just keep this methods in MyEventListener class and it will work like a charm:)
Here's the code :

private String generateRandomFilename(Throwable arg0) {
        Calendar c = Calendar.getInstance();
        String filename = arg0.getMessage();
        int i = filename.indexOf('\n');
        filename = filename.substring(0, i).replaceAll("\\s", "_").replaceAll(":", "") 
        + ".jpg";
        filename = "" + c.get(Calendar.YEAR) +
                "-" + c.get(Calendar.MONTH) +
                "-" + c.get(Calendar.DAY_OF_MONTH) +
                "-" + c.get(Calendar.HOUR_OF_DAY) +
                "-" + c.get(Calendar.MINUTE) +
                "-" + c.get(Calendar.SECOND) +
                "-" + filename;
        return filename;
    }

    private String generateFolderName() {
        Calendar c = Calendar.getInstance();
        String folderName = "";
        folderName = "/FailureScreenshots/" + c.get(Calendar.YEAR) +
                "-" + c.get(Calendar.MONTH) +
                "-" + c.get(Calendar.DAY_OF_MONTH)+
                "/";
        return folderName;
    }

    private void createScreenCaptureJPEG(String filename) {
        try {
            BufferedImage img = getScreenAsBufferedImage();
            String folderPath = System.getProperty("user.dir")+generateFolderName();
            // creating folder object
            File folder  = new File(folderPath);
            // if folder doesn't existing then create it
            if (!folder.exists()){
                folder.mkdirs();
            }
            File output = new File(folderPath+filename);
            ImageIO.write(img, "jpg", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BufferedImage getScreenAsBufferedImage() {
        BufferedImage img = null;
        try {
            Robot r;
            r = new Robot();
            Toolkit t = Toolkit.getDefaultToolkit();
            Rectangle rect = new Rectangle(t.getScreenSize());
            img = r.createScreenCapture(rect);
        } catch (AWTException e) {
            e.printStackTrace();
        }
        return img;
    }

I would like to thank Darrell Grainger for his post from where i actually took most of the code and modified a little bit for my purposes. My final result you can see here.

Hope you will find this article useful. Thanks.

comments powered by Disqus
comments powered by Disqus