2017-08-03 37 views
1

我已經使用Selenium在Java中編寫了我的代碼。當我運行代碼時,它拋出了一個NullPointerException。檢查下面在我的代碼中的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", "[email protected]"); 
    } 
    } 
+0

您還沒有調用'launchApplication'方法,其中實際初始化webdriver對象。 – Barney

+0

[什麼是NullPointerException,可以如何修復它?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) – JeffC

回答

0

這裏是回答你的問題:

你看到一個NullPointerException因爲main()您試圖訪問loginApplication()方法在開始,這需要一個WebDriver的活動實例,即driverfindElement(By.name("username")); & findElement(By.name("password"));並在HTML DOM上執行sendKeys()方法。

解決方案將首先訪問launchApplication()方法,因此您有一個活動實例driverIE 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", "[email protected]"); 
    obj.closeBrowser(); 
    } 

} 

讓我知道如果這個回答你的問題。

相關問題