首页 > 解决方案 > 在 Java 中使用 Cucumber,我可以在一个项目中使用 2 个 ServiceHooks 类吗?

问题描述

我想使用具有 UI 和 API 功能的 Cucumber 和 Java 创建一个测试框架。我可以使用带有 @Before 注释的 ServiceHooks 类来运行 UI 测试的一些先决条件,并使用带有另一个 @Before 注释的另一个 ServiceHooks 类在 API 测试之前运行一些先决条件吗?

如果是,我将如何告诉黄瓜在运行测试时使用哪一个?

这是 TestRunner 类:

import cucumber.api.CucumberOptions;
import cucumber.api.SnippetType;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.PickleEventWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

@CucumberOptions(
        features = "src/test/resources/features",
        glue = {"stepDefs"}, // this is a package in which I have the ServiceHooks class and the StepDefinitions class
        snippets = SnippetType.CAMELCASE,
        tags = {"not @Ignore"}
       ,
        plugin = {
                "pretty",
                "html:target/cucumber-reports/cucumber-pretty",
                "json:target/cucumber-reports/CucumberTestReport.json",
                "rerun:target/cucumber-reports/rerun.txt"
        }


        )
public class TestRunner {
    private TestNGCucumberRunner testNGCucumberRunner;

    @BeforeClass(alwaysRun = true)
    public void setUpClass() throws Exception {
        testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
    }

    @Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "scenarios")
    public void scenario(PickleEventWrapper pickleEvent, CucumberFeatureWrapper cucumberFeature) throws Throwable {
        testNGCucumberRunner.runScenario(pickleEvent.getPickleEvent());
    }

    @DataProvider
    public Object[][] scenarios() {
        return testNGCucumberRunner.provideScenarios();
    }

    @AfterClass(alwaysRun = true)
    public void tearDownClass() throws Exception {
        testNGCucumberRunner.finish();
    }
}

标签: seleniumautomated-testscucumbercucumber-java

解决方案


您可以使用带标签的钩子并使用相关标签(例如@api@browser.

来自标记钩子的黄瓜文档:“可以根据场景的标签有条件地选择要执行的钩子。要仅针对某些场景运行特定的钩子,您可以将之前或之后的钩子与标记表达式相关联。

注释方法样式:

@After("@browser and not @headless")
public void doSomethingAfter(Scenario scenario){
}

拉姆达风格:

After("@browser and not @headless", (Scenario scenario) -> {
});

"


推荐阅读