javaseleniumcucumberdriversaucelabs

RemoteWebDriver is null error (sauce labs implementation) -selenium,cucumber,java


I am implementing my code to work on remote machines on Sauce Labs. The code worked fine until I have changed my driver initialisation (to work with remote server). I keep getting this.driver is null exception. I don't know what's wrong with it, I was following official documentation and tried many things. I hope someone can see the issue here. Thank you in advance. My code:

DRIVER:(my username and key are copied from my sauce labs account, renamed for this purpose)

public class Hooks {
    public RemoteWebDriver driver;
    public WebDriverWait wait;

    @Before
    public void setup(Scenario scenario) throws MalformedURLException {
        String username = System.getenv("my username");
        String accessKey = System.getenv("key");

        ChromeOptions chromeOpts = new ChromeOptions();
        MutableCapabilities sauceOpts = new MutableCapabilities();

        sauceOpts.setCapability("name", scenario.getName());
        sauceOpts.setCapability("username", username);
        sauceOpts.setCapability("accessKey",accessKey);

       MutableCapabilities browserOptions = new MutableCapabilities();
       browserOptions.setCapability(ChromeOptions.CAPABILITY, chromeOpts);
       browserOptions.setCapability("sauce:options", sauceOpts);
       browserOptions.setCapability("browserName", "chrome");
       browserOptions.setCapability("browserVersion", "latest");
       browserOptions.setCapability("platformName", "Windows 10");

       String sauceUrl = "https://ondemand.us-west-1.saucelabs.com:443/wd/hub";
       URL url = new URL(sauceUrl);
       driver = new RemoteWebDriver(url, browserOptions);
       wait = new WebDriverWait(driver, Duration.ofSeconds(10));



    }

    @After
    public void tearDown(Scenario scenario) {driver.quit();}
}

PAGE OBJECT WHERE MY CODE IS: (shortened for privacy purposes)

public class LandingPO extends Hooks {

 static RemoteWebDriver driver;
 static WebDriverWait wait;
 String url = "https://google.com"
 public void openUrl() {
        driver.get(url);}

And then I just call this method (landingPO.openUrl();) in my stepDefinition class. The error is thrown where first driver usage is found:

Step failed
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.remote.RemoteWebDriver.get(String)" because "pageObjects.LandingPO.driver" is null

it breaks right at "driver.get(url)" in my LandingPO


Solution

  • If anyone will have the same problem, the answer was:

    I was using wrong Before/After import. The correct import should be:

    import io.cucumber.java.After; import io.cucumber.java.Before;