Search code examples
cucumber-jvmcucumber-javaassertj

How to attach/embed captured screenshots during custom softAssertion into Cucumber Report?


In soft assertion screenshot get captured when softAssertions.assertAll() is called. So to capture screenshots for each soft Assertion failure, created simple CustomAssertion which extends to SoftAssertions and in that override a method name onAssertionErrorCollected().

Below is the sample code.

public class CustomSoftAssertion extends SoftAssertions {

    public CustomSoftAssertion() {
    }

    @Override
    public void onAssertionErrorCollected(AssertionError assertionError) {
        File file = TestRunner.appiumDriver.getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(file, new File(System.getProperty("user.dir") + File.separator + "ScreenShots" + File.separator + LocalDate.now().format(DateTimeFormatter.ofPattern("MMMM_dd_yyyy")) + File.separator + "demo.png"), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the step definition file:

CustomSoftAssertion softAssertion = new CustomSoftAssertion();
softAssertion.assertThat(isLogin).isTrue();

Above code is working properly. But, how to this captured attach/embed this screenshots into the cucumber report? Note: For Assertion I am using Assertj library.


Solution

  • You attach scenarios to the report by using scenario.attach. This means you'll have to setup some plumbing to get the scenario into the assertion.

    public class CustomSoftAssertion extends SoftAssertions {
    
        private final Scenario scenario;
    
        public CustomSoftAssertion(Scenario scenario) {
            this.scenario = scenario;
        }
    
        @Override
        public void onAssertionErrorCollected(AssertionError assertionError) {
            // take screenshot and use the scenario object to attach it to the report
            scenario.attach(....)
        }
    }
    
    
    private CustomSoftAssertion softAssertion;
    
    @Before
    public void setup(Scenario scenario){
        softAssertion = new CustomSoftAssertion(scenario);
    }
    
    @After // Or @AfterStep
    public void assertAll(){
        softAssertion.assertAll();
    }
    
    @Given("example")
    public void example(){
        softAssertion.assertThat(isLogin).isTrue();
    }