feature.StepDefinitions cucumber中的java.lang.NullPointerException

时间:2016-02-21 18:27:09

标签: selenium selenium-webdriver cucumber

我得到NullPointerException如下:

功能:登录操作

情景:

Successful Login with Valid Credentials # C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:3
Given User is on Home Page                      # StepDefinitions.User_is_on_Home_Page()
When User enters UserName and Password          # StepDefinitions.User_enters_UserName_and_Password()
  java.lang.NullPointerException
    at feature.StepDefinitions.User_enters_UserName_and_Password(StepDefinitions.java:25)
    at ?.When User enters UserName and Password(C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:5)

Then Message displayed Login Successfully       # StepDefinitions.Message_displayed_Login_Successfully()

代码:

package feature;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class StepDefinitions {
  public static WebDriver driver;

  @Given("^User is on Home Page$")
  public void User_is_on_Home_Page() throws Throwable {
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://opensource.demo.orangehrmlive.com/");
 }

  @When("^User enters UserName and Password$")
  public void User_enters_UserName_and_Password() throws Throwable {
    driver.findElement(By.name("txtUsername")).sendKeys("admin");
    driver.findElement(By.xpath("//input[@id='txtPassword']")).sendKeys("admin");
    driver.findElement(By.name("Submit")).click();
    Thread.sleep(3000);
  }

  @Then("^Message displayed Login Successfully$")
  public void Message_displayed_Login_Successfully() throws Throwable {
      System.out.println("login completed");
  }
}

1 个答案:

答案 0 :(得分:1)

User_is_on_Home_Page()中,您在该方法中使用名为driver的局部变量。您没有设置其他方法正在使用的静态 driver。因此,当他们引用driver时,它仍为空。

解决方案是改变:

public static WebDriver driver;

为:

public static final WebDriver driver = new FirefoxDriver();

并从WebDriver driver = new FirefoxDriver();中删除User_is_on_Home_Page()行,以便它同样引用静态实例。

或者,懒惰地实例化静态驱动程序实例。替换:

WebDriver driver = new FirefoxDriver();
<{1>}中的

User_is_on_Home_Page()