Take screenshots in failed scenarios

There are scenarios where our test case fails and we use mostly logs to see what actions performed and how our test case failed,
but some times when we need to see the screenshot of what exactly happened on the browser while running scripts...
Even manual QA folks take screenshots of the AUT in cases of test case fails or passes... [kind of proof to the execution]

So the same, we can take screenshots in automation as well.

below is one example, where we are validating with valid credentials to login to gmail,
if logged in, check to see inbox link should display and make test case pass
else, make test case fail as our valid credentials did not work

package testPkg;
 
import java.io.File;
import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.apache.commons.io.FileUtils;
 
public class ScreenShot {
 static WebDriver driver;
public static void main(String[] args) throws IOException {
 try{
 driver = new FirefoxDriver();
 
 driver.get("http://www.gmail.com");
 driver.manage().deleteAllCookies();
 driver.findElement(By.id("Email")).sendKeys("skp1985");
 driver.findElement(By.id("next")).click();
 WebDriverWait wait = new WebDriverWait(driver, 5);
 wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("Passwd"))));
 driver.findElement(By.id("Passwd")).sendKeys("skp1985");
 driver.findElement(By.id("signIn")).click();
 //Once we enter uname and password, we expect the page should display with inbox
 //we are checking if the inbox link is present after login to make testcase pass
 wait = new WebDriverWait(driver, 6);
 wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.partialLinkText("Inbox"))));
 System.out.println("TestCase Pass");
 }
 catch(Exception e){
  //If inbox not present, then login credentials did not work and test case failed
  //so take screenshot to make sure it din't login
 System.out.println("TestCase Fail"+e.getMessage());
 TakesScreenshot ts = (TakesScreenshot)driver;
 File f = ts.getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(f, new File("./1.jpg"));}
 }
}


No comments:

Post a Comment