Search code examples
junit5allureselenide

How do I add a screenshot to an Allure report?


I have a Selenide+Java project which uses allure reporting. I am using the TestExecutionListener to handle browser setup, but I am having some extreme difficulty figuring out how to add screenshots to the report on a test failure.

I'm using

<dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit5</artifactId>
        <version>2.13.0</version>
        <scope>test</scope>
    </dependency>

And in my Listener code:

public class BrowserListener implements TestExecutionListener {

    Browser browser;

    @Override
    public void executionStarted(TestIdentifier testIdentifier) {
        if(testIdentifier.isTest()) {
            browser = new Browser();
            browser.openBrowser();
        }
    }

    @Override
    public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
            //code here to log failed execution - ideally would like to put screenshot on failure
            browser.close();
    }
}

How do I add a screenshot to an Allure report using Selenide/Junit 5?


Solution

  • I managed to get this working by adding the following:

    import com.codeborne.selenide.Configuration;
    import com.codeborne.selenide.Selenide;
    import com.codeborne.selenide.WebDriverRunner;
    import org.apache.commons.io.FileUtils;
    import org.junit.platform.engine.TestExecutionResult;
    import org.junit.platform.launcher.TestExecutionListener;
    import org.junit.platform.launcher.TestIdentifier;
    import org.openqa.selenium.NoSuchSessionException;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    
    import java.io.File;
    import java.io.IOException;
    
    import static com.codeborne.selenide.Selenide.open;
    import static com.codeborne.selenide.WebDriverRunner.getSelenideDriver;
    import static io.qameta.allure.Allure.addAttachment;
    
    
    @Override
    public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
    if (testExecutionResult.getStatus().equals(TestExecutionResult.Status.FAILED)) {
            try {
                File screenshotAs = ((TakesScreenshot) getSelenideDriver().getWebDriver()).getScreenshotAs(OutputType.FILE);
                addAttachment("Screenshot", FileUtils.openInputStream(screenshotAs));
            } catch (IOException | NoSuchSessionException e) {
                // NO OP
            } finally {
                WebDriverRunner.getSelenideDriver().getWebDriver().quit();
            }
        }
    }