小编典典

我的代码中为NullPointerException。怎么处理

selenium

我已经使用Selenium用Java编写了代码。当我运行代码时,它将引发NullPointerException。检查以下异常

Exception in thread "main" java.lang.NullPointerException
    at AdminInterface.loginApplication(AdminInterface.java:17)
    at AdminInterface.main(AdminInterface.java:29)

我的代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AdminInterface {
    public WebDriver driver;
    public void launchApplication() throws Exception
    {
        System.setProperty("webdriver.ie.driver", "C:\\Users\\rprem\\Downloads\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe");
        driver = new InternetExplorerDriver();
        driver.get("https://www.gcrit.com/build3/admin/");
    }
    public void loginApplication(String Username, String Password)
    {
        driver.findElement(By.name("username")).sendKeys(Username);
        driver.findElement(By.name("password")).sendKeys(Password);
        driver.findElement(By.id("tbd1")).click();
    }
    public void closeBrowser()
    {
        driver.close();
    }
    public static void main(String[] args) 
    {
        AdminInterface obj = new AdminInterface();
        obj.loginApplication("admin", "admin@123");
    }
    }

阅读 282

收藏
2020-06-26

共1个答案

小编典典

您会看到一个NullPointerException原因,因为main()您从一开始就尝试访问该loginApplication()方法,这需要in的活动实例,WebDriverdriverto
findElement(By.name("username"));findElement(By.name("password"));and
perform sendKeys()方法HTML DOM

解决方案是先访问该launchApplication()方法,以便您拥有driverand 的活动实例IE Browser。接下来,您可以访问loginApplication()方法。

这是您的工作代码块:

package demo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class Q45474353_NPE 
{

    public WebDriver driver;
    public void launchApplication()
    {
        System.setProperty("webdriver.ie.driver", "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe");
        driver = new InternetExplorerDriver();
        driver.get("https://www.gcrit.com/build3/admin/");
    }

    public void loginApplication(String Username, String Password)
    {
        driver.findElement(By.name("username")).sendKeys(Username);
        driver.findElement(By.name("password")).sendKeys(Password);
        driver.findElement(By.id("tbd1")).click();
    }

    public void closeBrowser()
    {
        driver.close();
    }

    public static void main(String[] args) 
    {
        Q45474353_NPE obj = new Q45474353_NPE();
        obj.launchApplication();
        obj.loginApplication("admin", "admin@123");
        obj.closeBrowser();
    }

}
2020-06-26