多个@Before/@After 与 Cucumber 和 Spring?

Multiple @Before/@After with Cucumber and Spring?

我不了解 Cucumber 配置,也找不到任何相关示例。

文件夹结构:

src/
 |-test/
    |-resources/
    |  |-cucumber/
    |     |-auth/
    |     |  |-Login.feature
    |     |-contributions/
    |        |-ClearanceCertificates.feature
    |-java/
       |-de/
          |-vbg/
             |-other/
                |-again/
                   |-important/
                      |-cucumber/
                      |  |-auth/
                      |  |  |-LoginStepDefinitions.java
                      |  |-contributions/
                      |     |-ClearanceCertificatesStepDefinitions.java
                      |-CucumberBase.java
                      |-SeleniumApplicationTests.java

CucumberBase.java:

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources",
    plugin = {"pretty", "html:build/reports/tests/test/cucumber.html"})
public class CucumberBase {}

SeleniumApplicationTests.java:

@CucumberContextConfiguration
@SpringBootTest
class SeleniumApplicationTests {}

*StepDefinitions.java 都定义了 @Before@After。我的假设是 StepDefinitions 与基于 location/package.

*feature 文件相匹配

虽然在我的测试中,Login.feature 执行 ClearanceCertificatesStepDefinitions.java 中定义的 @After

应该如何正确配置?

粘合路径上的所有步骤定义和挂钩都是全局的。因此所有场景都可以访问粘合路径上的所有步骤定义,并且粘合路径上的所有挂钩都会在每个场景中执行before/after。

如果您有只应针对特定场景执行的挂钩,您可以使用条件挂钩。要 运行 特定场景的特定挂钩,您可以将 Before 或 After 挂钩与标记表达式相关联。

Feature: Example

  @browser
  Scenario: Open a browser window
    ...
   
  @headless
  Scenario: Make a http call
    ...
@After("@browser and not @headless")
public void doSomethingAfter(Scenario scenario){
  // only executed after "Open a browser window"
}

https://cucumber.io/docs/cucumber/api/#conditional-hooks


或者,您可以更改代码的组织。

 |- src/test/java/com/example/one/RunCucumberTest1.java
 |- src/test/resources/com/example/one/example-1.feature

 |- src/test/java/com/example/two/RunCucumberTest2.java
 |- src/test/resources/com/example/two/example-2.feature
  
 |- src/test/java/com/example/common/AbstractCucumberTest.java
 |- src/test/java/com/example/common/SeleniumApplicationTests.java
@RunWith(Cucumber.class)
@CucumberOptions(extraGlue = "com.example.common")
public abstract class AbstractCucumberTest {}
public class RunCucumberTest1 extends AbstractCucumberTest {}
public class RunCucumberTest2 extends AbstractCucumberTest {}

Cucumber 将扫描 运行ner 的包以查找胶水和特征,因此可以省略胶水和特征路径。通过设置 extraGlue 属性 通用配置不必重复。