I am trying to run tests in Chrome headless mode but getting java.lang.NullPointerException
Chrome version: Version 72.0.3626.121 (Official Build) (64-bit)
Selenium version: 3.8.1
Chromedriver version: 2.45.615355
Here is my BaseTest:
public abstract class BaseTest {
public WebDriver driver;
protected abstract String getUrl();
@Before
public void setUp() {
Log.startLog("Test is Starting...");
System.setProperty("webdriver.chrome.driver", "src//test//resources//chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(getUrl());
}
@After
public void tearDown() {
Log.endLog("Test is Ending...");
driver.manage().deleteAllCookies();
driver.close();
}
}
When I'm running tests, not in headless mode every test works good but in headless mode, I can't even run a simple test to understand if the headless mode is working or not.
Test example:
@Test
public void test() {
System.out.println(driver.getTitle());
}
Example URL: https://www.wikipedia.org/
UPDATE: I've created new sample project with this code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class test {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/Users/alexsomov/Desktop/chromedriver2");
//Set Chrome Headless mode as TRUE
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
//Instantiate Web Driver
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com/");
System.out.println("Page title is - " + driver.getTitle());
driver.close();
}
And bingo, everything works well... Need to figure out why code above from real project doesn't work seems something wrong with BaseTest class and when I run code with debugger I'm getting driver == null, maybe anyone have a solution how I can solve this problem :/
ANSWER The solution was super easy, just need to change 1 string in setUp() method in BaseTest class.
This one:
WebDriver driver = new ChromeDriver(chromeOptions);
change to this:
driver = new ChromeDriver(chromeOptions);
and everything will work.