NullPointerException in my code. How to deal with it

后端 未结 1 1206
北海茫月
北海茫月 2020-11-30 15:11

I\'ve written my code in Java using Selenium. When I run the code, it\'s throwing a NullPointerException. Check the exception below

Exception in thread \"mai         


        
相关标签:
1条回答
  • 2020-11-30 15:34

    You are seeing a NullPointerException because from main() you are trying to access the loginApplication() method right in the begining, which requires an active instance of the WebDriver i.e. the driver to findElement(By.name("username")); & findElement(By.name("password")); and perform sendKeys() method on the HTML DOM.

    The solution would be to first access the launchApplication() method so you have an active instance of driver and IE Browser. Next you can access loginApplication() method.

    Here is your working code block:

    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();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题