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(); 
 }
}
João Farias
11.2k2 gold badges21 silver badges41 bronze badges
asked Jun 9, 2018 at 18:23
1
  • 1
    There are numerous similar questions here. with answers. Commented 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

answered Jun 11, 2018 at 12:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.