Screenshot operation of java selenium

Article directory


Selenium screenshot operation is a common WebUI operation. Here is a detailed introduction of how to implement screenshot operation and the whole process of selenium project failure screenshot

Prerequisite

The project is a maven project and requires the following dependency packages:

  • selenium-java
  • selenium-api
  • commons-io

Since you are the selenium project to implement screenshot, the basic selenium Java dependency package is required. Then the TakesScreenshot class and OutputType.FILE are used in the selenium API in the following code. Then the FileUtils class is also used in the Commons IO package

Core code

// Screenshot operation
File sourcefile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Screenshot storage
FileUtils.copyFile(sourcefile, new File(screenshotPath + File.separator + screenshotName + screenshotFormat));

The above is the core code. screenshotPath is the storage path of screenshots relative to the project. screenshotName is the name set for screenshots. screenshotFormat is of String type, indicating whether screenshots are of. png or. jpg type
Of course, screenshots can be taken in case of failure. If you want to be flexible, you can not only take screenshots in case of failure, but this code can be placed flexibly. It is also feasible to take screenshots in case of a certain operation

Now I'll explain in detail how selenium makes the whole process of failure screenshots

Step 1: add dependency

By default, you have selenium Java dependency. Note that I did not refer to commons IO dependency package, but introduced htmlunit dependency package, because commons IO dependency exists in it

<dependency>
	<groupId>org.seleniumhq.selenium</groupId>
	<artifactId>selenium-api</artifactId>
	<version>3.141.59</version>
</dependency>
<dependency>
	<groupId>net.sourceforge.htmlunit</groupId>
	<artifactId>htmlunit</artifactId>
	<version>2.30</version>
</dependency>

Step 2: write a screenshot tool class

Add screenshot tool class ScreenshotUtil to util tool class package under the project. The driver in the lower part is converted into BaseTest test base class through ITestResult, and then take it from the base class. This test base class is the parent class of all test case classes, including drivers. Some people don't want to take drivers in this way. You can make drivers into static resources and then thread isolation (th Read local), and then take the driver directly in the screenshot method

public class ScreenshotUtil {
    /**
     * Exception screenshot storage path
     */
    private static String screenshotPath = System.getProperty("user.dir") + File.separator + "target" + File.separator + "test-output" + File.separator + "screenshot";

    /**
     * Abnormal screenshots
     *
     * @param iTestResult i test result
     * @param driver drive
     */
    public static void capture(ITestResult iTestResult) {
        // Get the driver that needs screenshots
        WebDriver driver = ((BaseTest)iTestResult.getInstance()).driver;
        // Screenshots
        File screenshotFile = new File(screenshotPath);
        // Create a folder if it does not exist
        if (!screenshotFile.exists() && !screenshotFile.isDirectory()) {
            screenshotFile.mkdirs();
        }
        // Screenshot format
        String screenshotFormat = ".png"
        // Which class causes the screenshot
        String className = iTestResult.getInstance().getClass().getSimpleName();
        // Time format
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year M month d day H Time m branch s second");
        String timeStr = simpleDateFormat.format(new Date());
        // Screenshot name
        String screenshotName = className + "-" + timeStr;
        try {
            // Screenshot operation
            File sourcefile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            // Screenshot storage
            FileUtils.copyFile(sourcefile, new File(screenshotPath + File.separator + screenshotName + screenshotFormat));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("Abnormal screenshot operation!");
        }
    }
}

Step 3: add a screenshot related listener

I need to write a listener class called TestLogListener. It needs to inherit TestListenerAdapter. TestListenerAdapter is a class provided by testng. This class is very convenient. It provides some methods for each stage of the test process. We can put some required operations in these stages to realize the completion when we reach a certain test stage Some operations. The onTestFailure method is executed when the test fails

public class TestLogListener extends TestListenerAdapter {
    /**
     * start
     *
     * @param iTestContext ITestContext
     */
    @Override
    public void onStart(ITestContext iTestContext) {
        super.onStart(iTestContext);
    }

    /**
     * Test start
     *
     * @param iTestResult ITestResult
     */
    @Override
    public void onTestStart(ITestResult iTestResult) {
        super.onTestStart(iTestResult);
    }

    /**
     * Test success
     *
     * @param iTestResult ITestResult
     */
    @Override
    public void onTestSuccess(ITestResult iTestResult) {
        super.onTestSuccess(iTestResult);
    }

    /**
     * Test failure
     *
     * @param iTestResult ITestResult
     */
    @Override
    public void onTestFailure(ITestResult iTestResult) {
        super.onTestFailure(iTestResult);
        // Throw an exception to screenshot in case of failure
        ScreenshotUtil.capture(iTestResult);
    }

    /**
     * Test skip
     *
     * @param iTestResult ITestResult
     */
    @Override
    public void onTestSkipped(ITestResult iTestResult) {
        super.onTestSkipped(iTestResult);
    }

    /**
     * End
     *
     * @param iTestContext ITestContext
     */
    @Override
    public void onFinish(ITestContext iTestContext) {
        super.onFinish(iTestContext);
    }
}

Step 4: testng.xml configuration listener

<listeners>
	<! -- listener with failure screenshot -- >
	<listener class-name="com.abcnull.listener.TestLogListener"/>
</listeners>

Step 5: view the failed screenshot

When we run testng.xml with assertion errors, we will find new screenshots with errors in target / test output / screenshot

137 original articles published, 44 praised, 60000 visitors+
Private letter follow

Tags: Selenium Java xml Maven

Posted on Tue, 28 Jan 2020 21:48:51 -0800 by Gimpy