A Totewar
A Totewar

Reputation: 11

How to add Screenshot in Extent Report for Passed Test Cases in Selenium cucumber framework

How to add Screenshot in Extent Report for Passed Test Cases in Selenium cucumber framework.

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

    }

Upvotes: 1

Views: 3930

Answers (2)

Using @After annotation, you shall be able to embed screen shot in your extent report. You can have if else block. One block for Failed Test & Other for Passed Test Case and here you write code to embed screen shot in report.

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

Upvotes: 1

Matthewek
Matthewek

Reputation: 1559

Use @After hook, and embed screenshot into cucumber report.

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

Upvotes: 0

Related Questions