Search code examples
javaseleniumjunitcucumbercucumber-junit

Cucumber JUnit : How to take screenshot when scenario step definitions are spread across classes?


I have a Feature File :

@Scenario_1
Scenario: Google search
Given user opens "google"
When user searches for "Hello World"
Then user sees the results


@Scenario_2
Scenario: Yahoo search
Given user opens "yahoo"
When user searches for "Hello World"
Then user sees the results


@Scenario_3
Scenario: Test w3schools links
Given I test w3schools
When I click on a link
Then the page refreshes with new data displayed


@Scenario_4
Scenario: Test database
Given I log into DB
When I query for UserID
Then the user details are displayed

The step definitions for these are split into 3 classes.

Since the statements are common for Scenario_1 and Scenario_2, their definitions are grouped in one class:

SearchStepDefinitions
{
    Scenario_1
    Scenario_2

    @Given(...)
    @When(...)
    @Then(...)
    @After(Scenario s)
    {
        final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);     //Take screenshot
        s.embed(screenshot, "image/png");
    }   

}

Scenario_3 statement definitions are in another class.

LinkStepDefinitions
{
    Scenario_3

    @Given(...)
    @When(...)
    @Then(...)
    @After(Scenario s)
    {
        final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);     //Take screenshot
        s.embed(screenshot, "image/png");
    }   

}

Scenario_4 statements are defined in another class.

DatabaseStepDefinitions
{
    Scenario_4

    @Given(...)
    @When(...)
    @Then(...)
}

I need screenshots for Scenarios 1,2,3 because they deal with front end. However, I do not want any screenshot for Scenario4 as it deals with backend.

I run the feature file :

1) Scenario_1 and Scenario_2 run fine.

2) When I run Scenario_3, I get NullPointerException at "//Take screenshot" of SearchStepDefinitions.

3) When I run Scenario_4, I get NullPointerException at "//Take screenshot" of SearchStepDefinitions.

How should I structure my program so that I can keep the statements in different classes, at the same time take screenshots as and when required ?


Solution

  • All of the@Before and @After annotations have the same scope so it is likely that the first one encountered is executed, well first, each time for all scenarios. You can specify which gets executed using a tag as an argument. Look for Tagged Hooks here.