1

lang.nullpointerexception while running the below code.

package aditi;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;

public class TestNG {

    public static WebDriver driverok ;

@Test
  public void main(){
    driverok.findElement(By.id("email")).sendKeys("[email protected]");
    driverok.findElement(By.id("pass")).sendKeys("Aasds");
    driverok.findElement(By.id("u_0_2")).click();
     System.out.println("login successfully");
  }

  @BeforeMethod
  public void beforeMethod() {
      System.setProperty("webdriver.chrome.driver", "E:\\selenium\\chromedriver.exe\\");
        WebDriver driverok = new ChromeDriver();
      driverok.get("https://www.facebook.com/");
      driverok.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  }

  @AfterMethod
  public void afterMethod() {
      driverok.quit(); 
  }
}
1
  • 1
    There are numerous similar questions here. with answers.
    – Alexey R.
    Jun 9, 2018 at 22:22

1 Answer 1

2

On your beforeMethod, you are creating a local object:

WebDriver driverok = new ChromeDriver();

This object is alive during the beforeMethod, but sent to the garbage collect right after.

In the main method, you are referencing to the instance driverok object, which was never initialized (null by default). Therefore, when you try to call findElement on null, you get a NullPointerException.

Changing the beforeMethod to the following will initialize the instance property, making the main method work correctly:

this.driverok = new ChromeDriver();

See this answer to more information about this: https://stackoverflow.com/a/3728075/2252076

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.