Search code examples
javacucumbercucumber-jvm

Cucumber hooks are being run, but not the tests


I'm getting the error: cucumber.runtime.CucumberException: Failed to instantiate class steps.MyStepdefs

Here's what I'm trying to do. My hooks are located in the package steps:

public class hooks {
    public static WebDriver webDriver;

    @Before
    public static void ChromeDriverSetup() {

        System.out.println("Creating new ChromeDriver instance...");
        webDriver = new ChromeDriver();

        System.out.println("Hello from hooks!");
    }

The above is executed...

But the MyStepdefs test class does not execute (it is also in the steps package) & I get the above error.

public class MyStepdefs {
   ProductPage productPageObjects = new ProductPage();


    @Given("I purchase {int} items of the same product")
    public void iPurchaseItemsOfTheSameProduct(int qty)  {

        System.out.println("Hello from MySteps!");
        productPageObjects.Visit();
        productPageObjects.ClickPlusQtyElement(qty);
    }
package pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import static steps.hooks.webDriver;

public class ProductPage {

    private WebElement totalQtyElement = webDriver.findElement(By.cssSelector(".sanitized"));
    private WebElement plusQtyElement = webDriver.findElement(By.cssSelector(".sanitized"));

    public void Visit() {
        webDriver.get("https://www.example.com");
    }


    public String ClickPlusQtyElement(int qty) {

        int minAmount = 1;
        while (minAmount < qty)
        {
            plusQtyElement.click();
            minAmount ++;

        }
        System.out.println("The amount is now: " + totalQtyElement.getText());

        return totalQtyElement.getText();
    }
}

In IntelliJ, my glue is set as steps. I also have a RunCucumberTest class in the steps package.

package steps;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(tags = "not @ignore", plugin = {"pretty", "html:target/cucumber"})
public class RunCucumberTest {}

Why does it not execute MyStepsdefs ?

stacktrace: https://pastebin.com/X5KhHfuP

Update: When I comment out calls to ProductPage the line System.out.println("Hello from MySteps!"); does get executed. So there is an issue with that particular call.


Solution

  • Ok I figured it out. When I try to instantiate the class ProductPage, I get an error due to the web driver calls i.e. private WebElement totalQtyElement = webDriver.findElement(By.cssSelector(".sanitized"));

    The problem is that I haven't visited a URL yet! So, I am going to put the above in a method and do some refactoring.