java - 如何从要获取步骤定义java代码的功能文件中获取场景名称

标签 java selenium automation cucumber bdd

我想从功能文件中获取场景的文本名称并将其存储到变量或在我的步骤定义中打印它。下面是我的代码:

功能文件:

Feature: Login
  I want to use this template for my feature file

  Scenario Outline: Login with correct credentials
    Given the user is on the login page

步骤定义:

public class Login implements Data{
    WebDriver driver;
    LoginPage loginPage;

    @Given("^the user is on the login page$")
    public void navigateToURL() {
        System.setProperty(DRIVER, DRIVER_LOCATION);
        driver = new FirefoxDriver();

        loginPage = new LoginPage(driver);
        loginPage.visit(BASE_URL);
        loginPage.clickLoginLink();

        //System.out.println("Testing Scenario" + *<scenario name>*)
    }
}

我想打印场景大纲文本:使用正确的凭据登录。感谢你的帮助。谢谢!

更新: 我尝试添加此代码,但抛出错误消息: TagExpressionParser exception

最佳答案

您可以添加一个Before Hook,并在hook内打印出场景名称,如下所示:

import cucumber.api.Scenario;
import cucumber.api.java.Before;

    @Before
    public void printScenarioName(Scenario scenario) {
        System.out.println("Run into Before Hook: printScenarioName");
        System.out.println("Print Scenario name in Before Hook: " + scenario.getName());
    }

下面是对 Maven pom.xml 的依赖

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- Test tools -->
    <junit.version>4.12</junit.version>
    <!-- Cucumber version -->
    <cucumber.version>1.2.5</cucumber.version>
</properties>

<dependencies>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java8</artifactId>
        <version>${cucumber.version}</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${cucumber.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

如果您不使用 Maven,请下载以下 jar 并将它们添加为项目库 enter image description here

以上代码在我的本地工作,您可以从 my github 获取它们

关于java - 如何从要获取步骤定义java代码的功能文件中获取场景名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48533246/

相关文章:

azure - 无法连接到在容器应用程序服务上运行的 selenium/standalone-chrome docker 容器

javascript - 如何单击 javascripted 单选按钮并使用 Python (urllib2) 获取下一页? [WebScrape, Selenium ]

c# - 使用 EnvDTE 自动化 Visual Studio

c# - 我们可以使用 UI 自动化来自动化远程机器吗

testing - Cypress - 选择一个选项而不使用文本或值

java - HttpsURLConnection 到 JSONObject 转换

Java - 深度克隆具有多种类型元素的 Vector

java - 在 Postgres 表中插入时间戳

Java - 多项式项的 toString 方法

python Selenium : stale element reference: element is not attached to the page document