如何解决java.lang.NullPointerException异常?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (125)

我得到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");
  }
}
提问于
用户回答回答于

将以下代码:

public static WebDriver driver;

改为:

public static final WebDriver driver = new FirefoxDriver();

扫码关注云+社区

领取腾讯云代金券