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

时间:2019-04-11 12:32:02

标签: selenium cucumber extentreports selenium-extent-report

如何在范围报告中为硒黄瓜框架中通过的测试用例添加截屏

@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());
        }

    }

2 个答案:

答案 0 :(得分:0)

使用 @After 钩子,并将屏幕截图嵌入黄瓜报告中。

@After(order = 0)
public void onScenarioFinished()
{
    byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)
    scenario.embed(driver.getScreenShotRaw(), "image/png");
}

答案 1 :(得分:0)

使用@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());
    }
}