我从别人那里继承了一个测试的大项目,主要的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/