我是Cucumber的新手,我正在尝试实现一个Hook类...简单来说,就是:driver.quit();。方法不起作用。

这是我的钩子类:

import cl.xxx.util.init.Initializer;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import org.openqa.selenium.WebDriver;


public class ServiceHooks {

    protected WebDriver driver;

    @Before
    public void initializeTest()throws Exception{
        // Code to setup initial configurations
        Initializer.getInstance().init();
    }

    @After
    public void embedScreenshot(Scenario scenario) {
        if (scenario.isFailed()) {
            try {
                System.out.println("Test finished with error");
                 driver.quit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


如果方案步骤中存在问题,则控制台将显示消息“测试已完成,但有错误”,但未关闭驱动程序。

这些是我的POM依赖项:

<dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm-deps</artifactId>
            <version>1.0.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>1.2.5</version>
            <scope>compile</scope>
            <exclusions>

            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>3.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-ie-driver</artifactId>
            <version>3.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-support</artifactId>
            <version>3.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.stephenc.monte</groupId>
            <artifactId>monte-screen-recorder</artifactId>
            <version>0.7.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-sandwich</artifactId>
            <version>0.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.github.mkolisnyk</groupId>
            <artifactId>cucumber-runner</artifactId>
            <version>1.0.10</version>
        </dependency>
        <dependency>
            <groupId>com.github.mkolisnyk</groupId>
            <artifactId>cucumber-reports</artifactId>
            <version>1.3.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-html</artifactId>
            <version>0.2.3</version>
        </dependency>
    </dependencies>


如果有人可以帮助我,请。

提前致谢。

我不知道它是否有用,但这是我的TestRunner:

import cucumber.api.CucumberOptions;
import cucumber.api.Scenario;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import org.junit.runner.RunWith;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.github.mkolisnyk.cucumber.runner.ExtendedCucumber;
import com.github.mkolisnyk.cucumber.runner.ExtendedCucumberOptions;
import com.github.mkolisnyk.cucumber.runner.ExtendedTestNGRunner;

//@RunWith(ExtendedCucumber.class)
@ExtendedCucumberOptions(jsonReport = "target/cucumber-reports/rodriguito/cucumber.json",
        retryCount = 3,
        detailedReport = true,
        detailedAggregatedReport = true,
        overviewReport = true,
        coverageReport = true,
        jsonUsageReport = "target/cucumber-reports/rodriguito/cucumber-usage.json",
        usageReport = true,
        toPDF = true,
        excludeCoverageTags = {"@flaky" },
        includeCoverageTags = {"@passed" },
        outputFolder = "target/",
        reportPrefix = "results-${user}")


@CucumberOptions(features = {"src/test/resource/features"},
                 glue={"stepdefs"},
                 monochrome = true,
                 tags = {"~@Ignore"},
                 plugin = {"pretty","html:target/cucumber-reports/cucumber-pretty",
                           "html:target/cucumber-reports/cucumber-html-report",
                           "json:target/cucumber-reports/CucumberTestReport.json",
                           "rerun:target/cucumber-reports/rerun.txt",
                           "usage:target/cucumber-usage.json"}
)
public class TestRunner extends ExtendedTestNGRunner{
    private TestNGCucumberRunner testNGCucumberRunner;

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

    @Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
    public void feature(CucumberFeatureWrapper cucumberFeature) {
        testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
    }

    @DataProvider
    public Object[][] features() {
        return testNGCucumberRunner.provideFeatures();
    }

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

最佳答案

假设以下文件结构

src/test/java/TestRunner.java
src/test/java/stepdefs/ServiceHooks.java
src/test/java/stepdefs/StepDefinitions.java
src/test/resource/features/demo.feature
pom.xml


并使用您的pom.xmlTestRunner然后

演示功能

Feature: Test Before and After hook

  Scenario: Test hooks for a non failing scenario
    Given a successfull step

  Scenario: Test hooks for a failing scenario
    Given a not successfull step


StepDefinitions.java

package stepdefs;
import org.testng.Assert;
import cucumber.api.DataTable;
import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class StepDefinitions {
    @Given("^a successfull step$")
    public void aSuccessfullStep() throws Throwable {
        System.out.println("a successfull step");
    }

    @Given("^a not successfull step$")
    public void aNotSuccessfullStep() throws Throwable {
        System.out.println("a not successfull step");
        Assert.fail();
    }
}


ServiceHooks.java-仅添加了一些日志记录

package stepdefs;

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

public class ServiceHooks {

//    protected WebDriver driver;

    @Before
    public void initializeTest()throws Exception{
//        Initializer.getInstance().init();
        System.out.println("Before hook");
    }

    @After
    public void embedScreenshot(Scenario scenario) {
        System.out.println("After hook");
        if (scenario.isFailed()) {
//            try {
//                System.out.println("Test finished with error");
//                driver.quit();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            System.out.println("action for failed scenario ...");
        }
    }
}


使用mvn test运行测试会产生以下输出

Running TestRunner
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator@532760d8
Feature: Test Before and After hook
Before hook
a successfull step
After hook
Before hook

  Scenario: Test hooks for a non failing scenario # demo.feature:3
    Given a successfull step                      # StepDefinitions.aSuccessfullStep()
a not successfull step
After hook
action for failed scenario ...

  Scenario: Test hooks for a failing scenario # demo.feature:6
    Given a not successfull step              # StepDefinitions.aNotSuccessfullStep()
      java.lang.AssertionError: null
        at org.testng.Assert.fail(Assert.java:94)
        at org.testng.Assert.fail(Assert.java:101)
        at stepdefs.StepDefinitions.aNotSuccessfullStep(StepDefinitions.java:22)
        at ✽.Given a not successfull step(demo.feature:7)


Failed scenarios:
demo.feature:6 # Scenario: Test hooks for a failing scenario

2 Scenarios (1 failed, 1 passed)
2 Steps (1 failed, 1 passed)
0m0.098s

java.lang.AssertionError: null
    at org.testng.Assert.fail(Assert.java:94)
    at org.testng.Assert.fail(Assert.java:101)
    at stepdefs.StepDefinitions.aNotSuccessfullStep(StepDefinitions.java:22)
    at ✽.Given a not successfull step(demo.feature:7)

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.78 sec <<< FAILURE!
feature(TestRunner)  Time elapsed: 0.15 sec  <<< FAILURE!
cucumber.runtime.CucumberException: java.lang.AssertionError: null
    at cucumber.api.testng.TestNGCucumberRunner.runCucumber(TestNGCucumberRunner.java:69)
    at TestRunner.feature(TestRunner.java:48)
Caused by: java.lang.AssertionError: null
    at org.testng.Assert.fail(Assert.java:94)
    at org.testng.Assert.fail(Assert.java:101)
    at stepdefs.StepDefinitions.aNotSuccessfullStep(StepDefinitions.java:22)
    at ✽.Given a not successfull step(demo.feature:7)


Results :

Failed tests:   feature(TestRunner): java.lang.AssertionError: null

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0


对于这两种已执行的方案,您都找到了字符串After hook,对于失败的方案,还找到了action for failed scenario ...

这意味着问题很可能位于您的另一段代码中。

09-09 21:48