1

如何在 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());
        }

    }
4

2 回答 2

1

使用@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());
    }
}
于 2019-04-11T15:26:13.907 回答
0

使用@After hook,将截图嵌入到黄瓜报告中。

@After(order = 0)
public void onScenarioFinished()
{
    byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)
    scenario.embed(driver.getScreenShotRaw(), "image/png");
}
于 2019-04-11T12:47:45.587 回答