【发布时间】:2017-08-03 11:08:30
【问题描述】:
我正在编写一个 Java 代码,它将在 Chrome 或 Firefox 中运行一个简单的自动化场景 - 取决于用户的输入。它开始运行(打开浏览器),但随后抛出 java.lang.NullPointerException。我以为我分配给驱动程序变量的 null 稍后会被覆盖,但事实并非如此。如何解决这个问题?谢谢!
package com.selenium;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Main {
public static void main(String[] args) throws InterruptedException {
// environment variable
System.setProperty("webdriver.chrome.driver", "C:\\Automation\\libs\\Drivers\\chromedriver.exe");
//WebDriver chromeDriver = new ChromeDriver();
System.setProperty("webdriver.gecko.driver", "C:\\Automation\\libs\\Drivers\\geckodriver.exe");
WebDriver driver = null;
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
System.out.println("Please enter 1 for Chrome or 2 for Firefox " + option);
if (option == 1)
{
WebDriver driver1= new FirefoxDriver();
}
else if
(option == 2)
{
WebDriver driver2 = new ChromeDriver();
}
else
System.out.println("Please enter a correct number " + option);
String baseURL = "https://login.salesforce.com/?locale=eu";
driver.get(baseURL);
WebElement userName = driver.findElement(By.id("username"));
userName.sendKeys("Yan");
WebElement password = driver.findElement(By.id("password"));
password.sendKeys("123456");
WebElement rememberCheckbox = driver.findElement(By.id("rememberUn"));
rememberCheckbox.click();
WebElement bLogin = driver.findElement(By.id("Login"));
bLogin.click();
}
}
【问题讨论】:
-
你能显示堆栈跟踪吗
-
False: WebDriver driver1= new FirefoxDriver();右:driver = newFireFoxDriver(),
-
您没有将变量
driver设置为null以外的任何值。您如何期望它会被“覆盖”?请注意,您正在创建新变量driver1和driver2,但这些当然不会对变量driver产生任何影响。 -
您只需在 if{} 中创建新驱动程序。只需像 if (option == 1) { driver1= new FirefoxDriver(); }
标签: java selenium exception null automation