Selenium | Take UI screenshots when script is executed

|
| By Webner

During testing a website with Selenium, function given below can take screenshot that can help us in cases like when testcase fails and we need the screenshot to see what happened on UI.

Here is function to take screenshot:

public void screenshot(WebDriver driver, String fileName) {
    try {
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
        String formattedDate = sdf.format(date);
        formattedDate.replace('/', '_');
        formattedDate.replace(':', '_');
        formattedDate.replace(' ', '_');
        System.out.println("Screenshot has been saved  " + formattedDate);
        // now copy the  screenshot to desired location using copyFile //method
        String fileName1 = "Register";
        fileName = fileName + "_" + formattedDate + "_" + fileName1 + ".PNG";
        // Path of the folder in which Screenshot will save.
        FileUtils.copyFile(src, new File("/home/sumit/Desktop/Payroll/ScreenShot/" + fileName));
    } catch (Exception e) {
        //something went wrong, handle here
    }
}

Once we have this method ready just call it where you want to take the screenshot, like see example below:

public static void main(String[] args) throws Exception {
    Add_an_employee e = new Add_an_employee();
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().setSize(new Dimension(1920, 1080));
    String appurl = "http://payroll.webnerserver.com/View/Login.php";
    driver.get(appurl);
    Thread.sleep(5000);
    driver.findElement(By.xpath("/html/body/div[2]/div/div/form/div/input[1]")).sendKeys("sumit5@webners.com");
    driver.findElement(By.xpath("/html/body/div[2]/div/div/form/div/input[2]")).sendKeys("Sumit0!!");
    driver.findElement(By.xpath("/html/body/div[2]/div/div/form/div/input[3]")).click();
    Thread.sleep(3000);
    driver.findElement(By.id("empnumber")).sendKeys(“Test”);
    Select select = new Select(driver.findElement(By.id("dept")));
    select.selectByVisibleText(“Test”);
    driver.findElement(By.id("address")).sendKeys(“Test”);
    driver.findElement(By.id("email")).sendKeys(“Test”);
    driver.findElement(By.id("pass")).sendKeys(“Test”);
    driver.findElement(By.id("contact")).sendKeys(“Test”);
    driver.findElement(By.id("mydate")).sendKeys(“Test”);
    driver.findElement(By.id("Desigination")).sendKeys(“Test”);
    driver.findElement(By.xpath("id('registration')/div[1]/div[1]/div[6]/div/label/input")).click();
    driver.findElement(By.id("addEmployee")).click();
    Thread.sleep(2000);

    e.screenshot(driver, "screenshot");
    Thread.sleep(2000);
    driver.navigate().refresh();
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *