java - Cucumber:不允许扩展定义步骤定义或 Hook 的类

标签 java maven dependency-injection cucumber

我从别人那里继承了一个测试的大项目,主要的Java类是CommonSteps、CommonBase和CommonScript。它们目前以这种方式相关:

CommonSteps 扩展了 CommonBase

CommonBase 扩展了 CommonScript

当我尝试使用 mvn clean install 运行项目时,问题出在下一个方法上:

@After
public void tearDown(Scenario scenario) {
  if (scenario.isFailed()) {
    // Take a screenshot...
    final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    scenario.embed(screenshot, "image/png"); // ... and embed it in the report.
  }
}

我得到错误:

cucumber.runtime.CucumberException: You're not allowed to extend classes that define step definitions or hooks: steps.CommonSteps extends class common.CommonBase.

我如何开始使用依赖注入(inject)删除与继承相关的所有内容?

最佳答案

Cucumber 在每个场景之前创建定义 stepdefs 的所有类的新实例。 然后,只要需要运行一个步骤,它就会对这些实例中的一个调用 stepdef 方法。

如果你在类 A 中定义了一个 stepdef 方法 foo 并且你有一个类 B extends A 你会得到一个 a 和 b 实例。 foo 方法在两个实例上都可用,Cucumber 将无法决定在哪个实例上调用该方法。

这就是我们不允许这样做的原因。

解决方案是使用组合而不是继承。您可以通过依赖注入(inject)实现组合 - Cucumber 支持多种流行的 DI 框架。

关于java - Cucumber:不允许扩展定义步骤定义或 Hook 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985002/

相关文章:

java - 访问类并创建对象

java - JPA:当 child 有嵌入式ID时如何级联保存实体?

java - Maven WildFly 插件 : Could not execute goal deploy

java - 即使我提到了 mainClass 属性并且它就在它的 Nose 底下,Spring-boot maven 插件也无法找到 mainClass

java - 使用正则表达式匹配精确字符串

java后台/守护进程/服务跨平台最佳实践

java - 如何修复spring-boot中jdbc模板中的nullpointerException

c# - 以 Unity 作为 IoC 的 Rebus Servicebus

c# - 具有开放通用类型和依赖注入(inject)的 Microsoft 日志记录

c# - 如何在 BaseController 中初始化 BaseModel