Null pointer exception - driver null

Remek Szewczyk :

I am starting learning Selenium in Java and I have a big obstacle.

import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstTest {
    WebDriver driver;

    @Before
    public void driverSetup() {
        System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().setSize(new Dimension(1280, 720));
    }

    @After
    public void driverQuit() {
        driver.quit();
    }

    @Test
    public void getMethod() {
        driver.get("http://google.pl");
    }

}

I don't know how to solve it because in "getMethod" the driver is NULL.

Sameer Arora :

You have defined WebDriver driver; at the global level and then you are again defining and instantiating another WebDriver driver in the driverSetup method because of which the global driver never got instantiated.
You need to make a single line change in the driverSetup method and it would work.
Your driverSetup should be like:

@Before
public void driverSetup() {
    System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
    // Instantiating the global driver here
    driver = new ChromeDriver();
    driver.manage().window().setSize(new Dimension(1280, 720));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=370702&siteId=1