How to take Screenshots when test fails in Selenium?

This method is used to take snapshot on test fail. This method will create separate folder for each test Class and store snapshot everytime with qualified name that contains ClassName, method name and date time of screenshot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
 
/* 
*@param driver
*@param result
 
*/
 
 
public static void takeScreenshot(WebDriver driver, ITestResult result) throws Exception 
{
    DateFormat dateFormat = new SimpleDateFormat("MMMMM d yyyy");
    Date date = new Date();
    System.out.println(dateFormat.format(date));
 
    String current_Time = dateFormat.format(date);
 
    /** This is name of test method, annotated with @Test */
 
    String testMethod = result.getName();
 
    /** This is name of test class, from which, test method has run */
 
    String qualifiedTestClassName = result.getTestClass().toString();
 
    /** This is name of  tag of XML */
 
    String testName = result.getTestContext().getName();
 
    try 
    {
 
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
 
       System.out.println("Screenshot captured");
 
        /**
 
            * Split the qualified Test class name on dot
 
        */
 
        String[] qualifiedTestClass = qualifiedTestClassName.split("\\.");
 
        /**
 
        * Split the last index on ']' to get the Test class name
 
        */
 
        String testClass[] = qualifiedTestClass[qualifiedTestClass.length - 1].split("]");
 
        /**
 
        * Saving the screenshot as Test method name in folder with Test
 
        * class name
 
        */
 
        FileUtils.copyFile(scrFile, new File(SetUP.PATH_SCREENSHOT + testClass[0] + "/" + testMethod + "."
 
            + testName + "." + current_Time + ".jpg"));
 
       System.out.println("Screenshot saved to destination");
 
        } catch (Exception e) {
 
            System.out.println("Screenshot failed. " + new Object() {
 
        }.getClass().toString() + " | method " + new Object() {
 
               }.getClass().getEnclosingMethod().getName());
 
          System.out.println(e.getMessage());
 
       Reporter.log("Screenshot could not be captured");
 
    }
 
}

Shashank is an information technology graduate, keen observer and a perfection seeker. Passionate about browser as well as Robotic Process Automation