Taking screenshots while test fails

Open the project. If you forgot how to open project, see previous post.

Taking screenshot:

Add a new class named Utility under the Utils folder.

Now add following code into the java class:

package Utils;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

import java.io.File;
import java.io.IOException;

public class Utility {
    WebDriver driver;
    public Utility(WebDriver driver)
    {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }
    public void takeScreenShot(AndroidDriver driver) throws IOException {
        File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        String time = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss-aa").format(new Date());
        String fileWithPath = "./src/test/resources/screenshots/" + time + ".png";
        FileUtils.copyFile(screenshotFile, new File(fileWithPath));
    }
}

Add following command in build.gradle to resolve FileUtils.copyFIle reference error:

// https://mvnrepository.com/artifact/commons-io/commons-io
    compile group: 'commons-io', name: 'commons-io', version: '2.6'

Click on import icon to add library file.

Open TestCase.java file

Write this code where you want to take screenshot.

Suppose I want to take screenshot while just after login.

Here is the code.

Utility utility=new Utility(driver);
utility.takeScreenShot();

Now run the code and you will find the screenshot is saved into project folder.

Taking screenshot while test fails:

Write following code:

@AfterMethod  //AfterMethod annotation - This method executes after every test execution
    public void screenShot(ITestResult result) throws IOException {
        if(ITestResult.FAILURE==result.getStatus()){
            try{
                Utility utility=new Utility(driver);
                utility.takeScreenShot("fails.png");
            }
            catch (Exception exception){
                System.out.println(exception.toString());
            }

        }

    }

Now execute the project and you will get failed screenshot if there are any failure through assertion or network failure.

about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

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