Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Before doesn't execute in java Cucumber Step

Tags:

java

cucumber

bdd

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

like image 526
Programming Guy Avatar asked Jun 04 '14 04:06

Programming Guy


2 Answers

  1. 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.)

  2. Make sure your @Before method is public, not private.

like image 172
Matt Watson Avatar answered Sep 21 '22 05:09

Matt Watson


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.

like image 25
Julian Mesa Avatar answered Sep 24 '22 05:09

Julian Mesa