java如何正确地重用在其他功能类中编写的方法?
我有两个功能文件(FeatureA
和FeatureB
)。这些功能文件中的前两个步骤完全相同,因此我只想编写一次实现,然后可以被其他功能文件重用
Feature A
Given I use "<browser>"
When I navigate to the "www.google.com"
Then I will be able to do A
Feature B
Given I use "<browser>"
When I navigate to the "www.google.com"
Then I will be able to do B
我有父类Base
public class Base {
public LandingPage landingPage;
public synchronized void initiate(String browser) {
// Do usual Chrome / Firefox WebDriver instantiation
this.landingPage = new LandingPage(); // Instantiate landingPage
}
public synchronized void navigateTo(String URL, Scenario scenario) throws InterruptedException {
driver.get(URL);
}
}
我实现下面的Feature A
public class FeatureA extends Base {
@Given("I use {string}")
public void i_use(String browser) {
initiate(browser, scenario); // Call the method in parent class Base. This should instantiate this.landingPage = new LandingPage();
}
@When("I navigate to the {string}")
public void i_navigate_to_the(String URL) throws InterruptedException {
navigateTo(URL, scenario);
}
@Then("Then I will be able to do A")
public void then_i_will_be_able_to_do_A() {
//Do something specific to Feature A only
}
}
我实现了下面的Feature B
。(我在Feature A
中重新使用了步骤1和步骤2,因此不需要在Feature B
中重复它)
public class FeatureB extends Base {
@Then("Then I will be able to do B")
public void then_i_will_be_able_to_do_B() {
//Do something specific to Feature B only
log.debug("landingpage : " + super.landingPage); // Null. Not sure why?
}
}
当我运行Feature A
小黄瓜文件时,一切正常
当我运行Feature B
gherkin文件时,变量/reference super.landingPage
返回我null
我运行调试模式,可以看到initiate(browser, scenario);
已被调用,因此public LandingPage landingPage;
已被其他类(Class FeatureA
)实例化,在执行Feature B
中的步骤之前。但是Class FeatureB
看到null
那么,我如何使用功能A中的方法,并在功能B、C、D中重复使用它呢
# 1 楼答案
您可以通过依赖注入来实现这一点。依赖项注入允许您编写较小组件的步骤定义,这些组件可以通过其他组件的构造函数注入
最容易开始的是
cucumber-picocontainer
https://github.com/cucumber/cucumber-jvm/tree/main/picocontainer