问题
When i run the following class files in selenium, the browser is launched and URL is opened but error after that:
exception in thread "main" java.lang.NullPointerException
at guru99project.guru99project.printtitlepage(guru99project.java:25)
at guru99project.Main_method.main(Main_method.java:10)
Code trials:
package guru99project;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class guru99project {
public WebDriver driver;
public void invokechrome() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\A\\eclipse-workspace\\libs\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Dimension dim = new Dimension(640,480);
driver.manage().window().setSize(dim);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("http://demo.guru99.com/v4");
}
public void printtitlepage() {
System.out.println(driver.getTitle());
}
public void login (String uname, String pwd) {
WebElement usid = driver.findElement(By.name("uid"));
usid.sendKeys(uname);
// driver.findElement(By.name("uid")).sendKeys(uname);
driver.findElement(By.name("password")).sendKeys(pwd);
driver.findElement(By.name("btnLogin")).click();
}
}
package guru99project;
public class Main_method {
public static void main(String[] args) {
guru99project gp = new guru99project();
gp.invokechrome();
gp.printtitlepage();
gp.login("mnr160177", "hynydej");
}
}
回答1:
You already have defined driver as an instance of WebDriver globally (Class level) as:
public WebDriver driver;
So you don't need to define any other new instance of WebDriver within any of the methods()
within the same Class and keep on using the same globally defined instance of WebDriver i.e driver.
You need to remove WebDriver from the line:
WebDriver driver = new ChromeDriver();
So line would be:
driver = new ChromeDriver();
回答2:
You Already Specified as public WebDriver driver;
so you No Need to Specify again as ,
Webdriver driver = new ChromeDriver();//if you need This , Then Don't Specify public Webdriver driver at the Top. Initialize here it self and Import it.
Please Change The Above Line as ,
driver = new ChromeDriver();
来源:https://stackoverflow.com/questions/53024603/getting-error-exception-in-thread-main-java-lang-nullpointerexception