如何在 Cucumber 框架中正确使用 TestNG 注解

How to use correctly TestNG annotations with Cucumber framework

我正在构建 TestNG 和 Cucumber 框架,并希望使用像 @BeforeMethod, @AfterMethod 这样的 TestNG 注释,它将在每个场景前后使用 运行 setUptearDown 方法。如果我将所有 Cucumber 场景保存在单独的功能文件中,它就可以正常工作。但是如果我在同一个功能文件中有多个场景 @AfterMethod 不是每个场景之后 运行ning。

如果使用之前和之后的黄瓜也会有问题,只有当我把它们放在下面的 StepDefinition 文件中时它们才能正常工作:

public class StepDefinition extends Base {
    
    @Before
    public void setUp() throws Exception {
        openBrowser();
        maximizeWindow();
//      implicitWait(30);
        deleteAllCookies();
//      setEnv();
    }
    
    @After
    public void quit() throws IOException, InterruptedException {
        driver.quit();
    }

    @Given("^Navigate to ACT landing page$")
    public void navigate_to_ACT_landing_page() throws Throwable {
        LandingPage landingPage = new LandingPage();
        landingPage.navigateToLandingPage();
    }

    @Then("^Verify landing page is rendered$")
    public void verify_landing_page_is_rendered() throws Throwable {
        LandingPage landingPage = new LandingPage();
        landingPage.landingPageRendered();
    }

}

但是如果我将它们放在单独的 class 中(如下所示)它们就不起作用(在文档中说它们可以放在项目的任何地方)

package com.act.hooks;


import cucumber.api.java.After;
import cucumber.api.java.Before;

import java.io.IOException;

import com.moodys.act.base.Base;

public class Hooks extends Base {
    
    @Before
    public void setUp() throws Exception {
        openBrowser();
        maximizeWindow();
//      implicitWait(30);
        deleteAllCookies();
//      setEnv();
    }
    
    @After
    public void quit() throws IOException, InterruptedException {
        driver.quit();
    }

}

提供了黄瓜 tags/hooks @Before 和 @After 在每个场景之前和之后运行,您可以在其中包含设置和拆卸代码。您是否有任何特定原因想要使用 testng 注释来这样做?

这 link 可能对黄瓜 @Before 和 @After 标签有帮助。

https://www.google.com/amp/www.automationtestinghub.com/cucumber-hooks-before-after/amp/

Cucumber 不建议使用 TestNG 注释准备和清理状态。 为了最大限度地利用 TestNG,您可以尝试对 BDD with QAF. It considers each scenario as TestNGMethod.

使用纯 TestNG 实现

如果你想使用黄瓜那么你可以添加qaf-cucumber dependency and use TestNG factory. It will allow to use TestNG listeners and lifecycle methods (@BeforeMethod, @AfterMethod). When using cucumber with qaf you can choose either to utilize TestNG life-cycle or cucumber life-cycle.

此外,如果您使用的是 webdriver 或 appium,它具有内置的线程安全驱动程序管理,因此您无需担心驱动程序管理。