I've got a Cucumber Step class that i'm attempting to initialise a page model for all scenarios. So I added a @Before annotated method :
@Before()
private void beforeScenario() {
    LOGGER.info("Running before!");
    loginPage = BrowserDriver.getPageModel(LoginPage.class);
}
I've then got a bunch of steps that rely on loginPage being set. e.g.
@When("^I click the help link$")
public void I_click_the_help_link() {
    loginPage.clickHelpLink();
}
I have multiple Step classes. Both of the methods above are in the same same Step class. However loginPage is always null. The beforeScenario method is never being called. Have I completely misunderstood how @Before is meant to work? Any tips on how to get what I want to work?
Edit : I also have an @After annotated method that does get run after every scenario as expected.
Edit : Pom can be seen at : http://pastebin.com/PJ6qQRK9
Make sure you are using cucumber.annotation.Before rather than org.junit.Before.  Cucumber will not process JUnit annotations.  (More information in the Scenario Hooks section of this blog post.)
Make sure your @Before method is public, not private.
Hello I know that is an old post, but none of these solutions work for me. So I'm going to share my solution.
I created the class Hooks under the package: com.mycompany.automation.util
package com.mycompany.automation.util;
import com.mycompany.automation.rest.database.AS400DBManager;
import cucumber.api.java.After;
import java.sql.SQLException;
/**
 * @author <a href="[email protected]">Julian Mesa</a>
 * @version 0.1.0
 * @since 0.1.0
 */
    public class Hooks {
      @After
      public void beforeScenario() throws SQLException, ClassNotFoundException {
        System.out.print("Closing connection.");
        AS400DBManager.getInstance().closeConnection();
      }
    }
and then I specified the package in the glue options in the runner:
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = {"com.mycompany.automation.features.steps",
        "com.mycompany.automation.util"}
)
And it worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With