如何在Cucumber中链接功能和步骤定义

5

我对Cucumber java还不熟悉,在初始阶段遇到了这个问题: 由于某些原因,我没有使用MAVEN项目。我只是在eclipse中创建了一个简单的java项目。

我的特性文件位于“src/dummy/pkg/features”下,我的实现“StepDef.java”位于“src/dummy/pkg/features/implementation”下

我已经为Given、When和Then编写了步骤定义,但当我运行我的特性文件时,它无法识别实现。我该如何将特性与步骤定义链接起来?

4个回答

7

创建一个类YourClass,它应该像下面这样,并将其运行为JUnit测试。

@RunWith(Cucumber.class)

@CucumberOptions(  monochrome = true,
                     features = "src/dummy/pkg/features/",
                       format = { "pretty","html: cucumber-html-reports",
                                  "json: cucumber-html-reports/cucumber.json" },
                         glue = "your_step_definition_location_package" )

public class YourClass {
  //Run this from Maven or as JUnit
}

2
没错,我们必须在@CucumberOptions中使用glue =“pkg location”的粘合剂。 - user85

4
当您运行Runner类时,它将扫描所有在features选项中提到的功能文件,然后加载它们。之后,以glue选项中提到的文本开头的包中的所有步骤定义都将被加载。 例如:
@RunWith(Cucumber.class)
@CucumberOptions(
        plugin = { "pretty","json:target/cucumberreports.json" }, 
        glue = "stepDefinition", 
        features = "src/test/resources/TestCases/", 
        tags={"@onlythis"},
        dryRun=false
    )
public class RunTest {

}

这里所有位于

src/test/resources/TestCases/

的功能文件都会被加载,然后所有步骤定义都在其子目录中进行加载。

stepDefinition

每当来自功能文件的步骤被执行时,Cucumber将查找与步骤正则表达式相对应的函数并运行该函数。

例如,每当在src/test/resources/TestCases/Login.feature中运行步骤When User enters email id时,Cucumber会在所有步骤定义类中查找其相应的函数。

Login.feature
@LoginValidation 
Feature: To smoke test functionalities of app 

@Browser @ValidLogin 
Scenario: Verify scenario in case of successful login 
    When User enters email id 
    And User enters password 
    Then User clicks on sign in button and able to sign in 

当它到达 stepDefinition 子目录的类时,即在 stepDefinition.ui.home.LoginPageStepDef.java 中,cucumber 将查找带有 @When("^User enters email id$") 的函数并执行该函数。

LoginPageStepDef.java
public class LoginPageStepDef {

    LoginPage loginPage = new LoginPage(AttachHooks.driver);
    private static Logger LOGGER = Logger.getLogger(LoginPageStepDef.class);

    @When("^User enters email id$")
    public void user_enters_email_id() throws Throwable {
        //LoginPage.obj = loginPage;
        loginPage.enterEmailId(ConfigManager.getProperty("UserName"));
    }
}

2

您需要将项目转换为Cucumber项目。从Project Explorer中右键单击您的项目,然后选择Configure>Convert as Cucumber Project。


1
创建一个类似这样的运行器类,您应该能够执行。 也没有必要手动编写步骤定义,只需创建一个特性文件并运行它,它将创建一个步骤定义片段,可用于创建步骤定义类:
需要一个名为Runnerclass的类文件来运行cucumber:
@RunWith(Cucumber.class)
@CucumberOptions(plugin={"pretty","html:format"},

features = "Features/name.feature",glue={"path where step definitions exist"})
public class RunnerClass {

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接