1

I'm Beginner For Selenium Java Programming. When I'm Executing Below Script With TestNG I Face An Error.

Error Message

"java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "this.driver" is null"

Please Check Below Code And Suggest Changes.

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;

public class RegForm {
        
    public WebDriver driver; 
    
    @BeforeTest
    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver", "D://Selenium//ChromeDriver//chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("http://automationpractice.com/index.php");
        driver.manage().window().maximize();
        Thread.sleep(3000);
    }
        
    @Test
    public void TC01() throws Exception {
        driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/a")).click();
        Thread.sleep(3000);
        
    }

}
2

3 Answers 3

1

Just remove the WebDriver from the main try as below

public static WebDriver driver; 
@BeforeTest
public static void main(String[] args) throws Exception {
    System.setProperty("webdriver.chrome.driver", "D://Selenium//ChromeDriver//chromedriver");
    driver = new ChromeDriver();
    driver.get("http://automationpractice.com/index.php");
    driver.manage().window().maximize();
    Thread.sleep(3000);
}

If you are not using MAC then try to provide the chromedriver extension .exe, Also check the import for the @Test as you mentioned you are using testng

Sign up to request clarification or add additional context in comments.

Comments

0

Creating a driver in a test class is not the best idea.

It may be a good idea to implement something similar to this

Comments

0

Had the same issue wasted 1 full day in it. Please check if you have defined web driver in any other class or not. if yes then make it protected and extent it with this class.

protected static WebDriver driver;

Comments

Your Answer

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.