【问题标题】:Instantiating PageObject instances from within Cucumber StepDefinitions从 Cucumber StepDefinitions 中实例化 PageObject 实例
【发布时间】:2015-06-12 14:05:04
【问题描述】:

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

并完全按照演示对 PageObjects、Feature 文件和 StepDefs 文件进行了编码。但是,当我运行时,我在 Line16 处得到一个空指针异常,@When 方法中的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);

...一切都很开心。

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

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

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

【问题讨论】:

    标签: java selenium-webdriver cucumber bdd pageobjects


    【解决方案1】:

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

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

    这是一个基本的实践,因为只有:

    LandingPage landingPage
    

    表示你的landingPage变量被隐式赋值为空值;这就是你得到空指针异常的原因。

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多