在 Cucumber-jvm 中使用多个步骤定义时出现 NullPointerException

NullPointerException when using multiple stepdefinitions in Cucumber-jvm

我目前正在构建一个框架来测试 Rest-API 端点。由于我计划编写大量测试用例,因此我决定组织项目以允许我重用常见的步骤定义方法。

结构如下;

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

然而,当我尝试调用 SimpleSearchSteps.java 方法时,我得到一个 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);
    }

}

你能看看Karate it is exactly what you are trying to build ! Since you are used to Cucumber, here are a few things that Karate provides as enhancements (基于Cucumber-JVM)

  • 内置步骤定义,无需编写Java代码
  • 重复使用 *.feature 文件并从其他脚本中调用它们
  • 动态数据驱动测试
  • 并行执行测试
  • 能够运行某些例程每个功能仅一次

免责声明:我是开发者。

看起来你缺少 Cucumber 注释的 holder class,你应该有这样的东西,以便 Cucumber 知道并识别你的步骤和特征:

@RunWith(Cucumber.class)
@CucumberOptions(
    glue = {"com.example.functionaltest.features.steps"},
    features = {"classpath:functionaltest/features"}
)
public class FunctionalTest {
}

请注意,根据此示例,在您的 src/test/resources 中您应该有包含您的 .feature 文件的 functionaltest/features 文件夹,您可以根据您的设计更改它

我使用 RequestSpecBuilder in the AbstractEndpointSteps instead of RequestSpecification 的静态实例解决了这个问题。

因此,我能够完全避免重复 StepDefinitions 和 NPE 问题