Hello Friends,
We all know the importance of test evidences
in our test delivery. While raising a defect also, we need fail evidences that
helps developer to identify the issue and fix it.
Ok so now here we will see in detail, how can we capture the
fail test screens in web driver using TestNG
framework.
First we will create an Utility class with a method "captureScreenShot"
Below see the code:
package util;
import java.io.File;
import java.io.IOException;
import
org.apache.commons.io.FileUtils;
import
org.openqa.selenium.OutputType;
import
org.openqa.selenium.TakesScreenshot;
import
org.openqa.selenium.WebDriver;
public class utility
{
public static void
captureScreenShot(WebDriver driver , String screenshotName) throws IOException
{
TakesScreenshot ts =
(TakesScreenshot)driver;
File sourcefile =
ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sourcefile, new File("./Screenshots/" + screenshotName +".png"));
}
}
So we will use this method “captureScreenShot” in our test
where ever required to capture screenshot.
Now let’s create a class eg. Facebook.java where we will
create methods as our test cases for login validation. In addition we will
create a method “teardown” where we will use “ITesttResult” interface to manage
evidences. See how it done:
package testcases;
import java.io.IOException;
import
java.util.concurrent.TimeUnit;
import
org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import
org.testng.ITestResult;
import
org.testng.annotations.AfterMethod;
import
org.testng.annotations.Test;
import util.utility;
public class facebook {
WebDriver
driver;
@Test
public void login()
{
driver = new FirefoxDriver();
driver.get("https://facebook.com");
driver.manage().window().maximize();
driver.findElement(By.id("email")).sendKeys("Vishal");
driver.findElement(By.id("pass")).sendKeys("Sachan");
driver.findElement(By.id("u_0_m")).click();
driver.manage().timeouts().implicitlyWait(1000,
TimeUnit.SECONDS);
String
actual = driver.findElement(By.className("_1tp8")).getText();
Assert.assertEqual(actual,
"The
password that you've entered is incorrect");
driver.quit();
}
@AfterMethod
public void terdown(ITestResult
result) throws IOException
{
if(ITestResult.FAILURE==
result.getStatus())
{
utility.captureScreenShot(driver, result.getName());
}
}
}
If you see we have used ITestResult interface to get the status
of a method after run and using that status we apply a condition that is the
result(status) of method is failed, we call the captureSceenShot method of
utility class.
Here we are also saving the evidence name as its testcase(method
name). So it is compete test. You can add N number of test cases in this and
after every method run , 'teardown' will be executed and it used @AfterMethod annotation.
Please try this out and write in comments in case of any
issue faced.
No comments :
Post a Comment