How to take screenshot of failed test cases in Selenium Webdriver

Click here for Video tutorial

package testNGExamples;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;

public class RediffExample {
	WebDriver driver;

	@Test(priority = 1) // Actual Testing Activity Happens Here
	public void titleTest() {
		driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
		Assert.assertEquals(driver.getTitle(), "Rediffmail India");
	}

	@Test(priority = 2)
	public void rememberMeTest() {
		boolean actualStatus = driver.findElement(By.id("remember")).isSelected();
		Assert.assertEquals(actualStatus, false);
	}

	@AfterMethod
	public void afterMethod(ITestResult result) throws Exception{
		// System.out.println("Hi");
		if (result.getStatus() == ITestResult.FAILURE) {
			TakesScreenshot tc=(TakesScreenshot)driver; // Converted driver to takesScreenShot type
			File src=tc.getScreenshotAs(OutputType.FILE);  // It will take ScreenShot but will store into Java's buffer memory
			FileHandler.copy(src, new File(result.getName()+".png"));
		}
	}

	@BeforeTest // Pre-condition
	public void beforeTest() {
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\mprem\\OneDrive\\Desktop\\SelJars\\chromedriver_win32\\chromedriver.exe");
		driver = new ChromeDriver(); // Parent P=new Child  WebDriver driver=new ChromeDriver
	}

	@AfterTest // Post-Condition
	public void afterTest() {
		driver.quit();
	}
}

Comments