There are multiple ways to do this.
Create one separate class file as ScreenCapture and inside this class file create two methods.
One method is for when your particular testcase is run successfully and another method is for when your testcase is failed during execution of your test scripts.
I have provided you one class file.
package com.dummy;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
public class ScreenCapture {
public static void passScreenCapture() throws IOException
{
Date d = new Date();
System.out.println(d.toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); // Your each screenshot will be taken as this format "Year-Month-Date-Hours-Minutes-Seconds"
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\RND\\"+sdf.format(d)+".png")); //your screenshot path and convert date string to SimpleDateFormat because windows can't capture screenshot with(:)
}
public static void failScreenCapture() throws IOException
{
Date d = new Date();
System.out.println(d.toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HHmmss");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("D:\\RND\\"+sdf.format(d)+".png"));
}
}
Now your screenCapture class file is ready along with two different methods.
you need to call this methods, where you want to call.
You can directly call this methods to any class as follow.
ScreenCapture.passScreenCapture(); //classname.methodname
ScreenCapture.failScreenCapture();
OR
Another way as follow.
Create One class file as below.
package com.dummy;
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.testng.annotations.Test;
public class ScreenShots {
public void captureScreen() throws IOException
{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("D:\\RND\\Modulename.png"));
}
}
you call this methods to any class, and you can call this method as like this
public void captureScreen() throws Exception
{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("D:\\RND\\Modulepage.png"));
System.out.println("Module Page Screen is taken successfully.");
}