首页 > 解决方案 > 如何在 Selenium 黄瓜框架中通过测试用例的范围报告中添加屏幕截图

问题描述

如何在 Selenium 黄瓜框架中通过测试用例的范围报告中添加屏幕截图。

@After(order = 1)
public void after(Scenario scenario) throws IOException {

    TransferFiles files = new TransferFiles();
    String buildPath;
    String finalFile;

    if (scenario.isFailed()) {


        String screenshotName = scenario.getName().replaceAll(" ", "_") + "_" + String.valueOf(random);
        try {
            //This takes a screenshot from the driver at save it to the specified location
            File sourcePath = (((TakesScreenshot) TestBase.driver).getScreenshotAs(OutputType.FILE));
            File fileTempImg = new File("C:\\ScreenShot0011\\001temp001.png");
            FileUtils.copyFile(sourcePath, fileTempImg);

            InetAddress addr;
            addr = InetAddress.getLocalHost();

            buildPath = String.valueOf(fileTempImg).replaceAll("C:", addr.getHostName());
            finalFile = "//" + buildPath.replaceAll("\\\\", "/");
            //finalFile = "\\\\" + buildPath;

            files.transferFiles(finalFile, screenshotName, "png");

            //This attach the specified screenshot to the test
            addScreenCaptureFromPath("path/" + screenshotName + ".png");

            fileTempImg.delete();


        } catch (Exception e) {
            System.out.println("The specified file have not been found on the local machine:-" + e.getMessage());
        }

    }

标签: seleniumcucumberextentreportsselenium-extent-report

解决方案


使用@After 注释,您将能够在您的范围报告中嵌入屏幕截图。你可以有 if else 阻止。一个块用于失败的测试和其他用于通过的测试用例,在这里您编写代码以将屏幕截图嵌入报告中。

@After
public void afterScenario(Scenario scenario){
    try{
        if(scenario.isFailed()){
            // More code goes here.
        }else {
            //------------------------- Attaching Screen shot in the Report -------------------------
            byte[] screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        }
        ExtentManager.getReporter().flush();
    }
    catch(Exception e){
        scenario.write("WARNING. Failed to take screenshot with following exception : "+e.getMessage());
    }
}

推荐阅读