Search code examples
javarestcucumber-jvmrest-assuredcucumber-serenity

NullPointerException when using multiple stepdefinitions in Cucumber-jvm


I am currently building a framework to test a Rest-API endpoint. As I am planning to write a lot of test cases, I decided to organize the project to allow me to reuse common Step Definition methods.

The structure is as follows;

FunctionalTest
    com.example.steps
        -- AbstractEndpointSteps.java
        -- SimpleSearchSteps.java
    com.example.stepdefinitions
        -- CommonStepDefinition.java
        -- SimpleSearchStepDefinition.java`

However when I try to call SimpleSearchSteps.java methods I get a NullPointerException

CommonStepDefinition Code

package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;

import com.example.functionaltest.steps.AbstractEndpointSteps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;


public class CommonStepDefinition {

    @Steps
    private AbstractEndpointSteps endpointSteps;

    @Given("^a base uri \"([^\"]*)\" and base path \"([^\"]*)\"$")
    public void aBaseUriAndBasePath(String baseURI, String basePath) {
        endpointSteps.givenBasepath(baseURI, basePath);
    }

    @When("^country is \"([^\"]*)\"$")
    public void countryIs(String country) 
    {
        endpointSteps.whenCountry(country);
    }

    @Then("^the status code is (\\d+)$")
    public void theStatusCodeIs(int statusCode) {
        endpointSteps.executeRequest();
        endpointSteps.thenTheStatusCodeIs200(statusCode);
    }

}

SimpleSearchStepDefinition.java

package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;
import com.example.functionaltest.steps.EndpointSteps;
import cucumber.api.java.en.When;


public class SimpleSearchStepDefinition {

    @Steps
    private SimpleSearchSteps searchSteps;



    @When("^what is \"([^\"]*)\"$")
    public void whatIs(String what) {
        searchSteps.whenWhatIsGiven(what);
    }

}

Solution

  • I solved this issue by using a static instance of RequestSpecBuilder in the AbstractEndpointSteps instead of RequestSpecification.

    Therefore, I was able to avoid duplication of StepDefinitions and NPE issues altogether