gpt4 book ai didi

java - 从 Cucumber StepDefinitions 中实例化 PageObject 实例

转载 作者:太空宇宙 更新时间:2023-11-04 13:46:18 25 4
gpt4 key购买 nike

我正在尝试在线学习本教程: https://www.youtube.com/watch?v=x5Ru0f8uOqw&list=PL_noPv5wmuO_t6yYbPfjwhJFOOcio89tI&index=14

并完全按照演示对 PageObjects、Feature 文件和 StepDefs 文件进行了编码。但是,当我运行时,我在 @When 方法中的第 16 行 contactPage 处收到空指针异常。

public class StepDefinition {

WebDriver driver = new FirefoxDriver();
LandingPage landingPage;
ContactPage contactPage;

@Given("^I am on the zoo site$")
public void i_am_on_the_zoo_site() throws Throwable {
LandingPage landingPage = new LandingPage(driver);
landingPage.navigateToWebApp();
}

@When("^I click on \"(.*?)\"$")
public void i_click_on(String link) throws Throwable {
contactPage = landingPage.navigateToContactPage(link);
}

...所以我尝试在类的顶部实例化,如下所示:-

WebDriver driver = new FirefoxDriver();
LandingPage landingPage = new LandingPage(driver);
ContactPage contactPage = new ContactPage(driver);

...一切都很愉快。

我应该以这种方式实例化 pageobject 实例吗?最好的做法是什么?而且,为什么演示中的代码不会抛出空指针?

对于上下文,以下是相关的页面对象:摘要页:-

public class AbstractPage {

protected WebDriver driver;

public AbstractPage (WebDriver driver){
this.driver = driver;
}

public LandingPage navigateToWebApp(){
driver.navigate().to("http://thetestroom.com/webapp/");
return new LandingPage(driver);
}


public void closeDriver(){
driver.quit();
}
}

登陆页面:-

public class LandingPage extends AbstractPage {


public LandingPage(WebDriver driver) {
super(driver);
}

public ContactPage navigateToContactPage(String link){
driver.findElement(By.id(link.toLowerCase() + "_link")).click();
return new ContactPage(driver);
}
}

联系页面:-

public class ContactPage extends AbstractPage{


public ContactPage(WebDriver driver) {
super(driver);
}

public ContactPage setNameField(String value){

driver.findElement(By.name("name_field")).sendKeys(value);
return new ContactPage(driver);
}

//more setter methods

最佳答案

是的,您确实需要创建页面对象的新实例,即

LandingPage landingPage = new LandingPage(driver);
ContactPage contactPage = new ContactPage(driver);

这是一项重要的实践,因为:

LandingPage landingPage

意味着你的landingPage变量被隐式分配了一个空值;这就是您收到空指针异常的原因。

关于java - 从 Cucumber StepDefinitions 中实例化 PageObject 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com