0

So, I am learning Java, coming from Ruby and Python. I am writing selenium tests using WebDriver and cucumber, and this is basically what I have now:

CommonSteps.java

import org.openqa.selenium.WebDriver;
import cucumber.api.java.Before;

public class CommonSteps {

    public static WebDriver driver;

    @Before
    public void beforeScenario() {
        driver = new ChromeDriver();
    }

LoginSteps.java

import org.openqa.selenium.WebDriver;

public class LoginSteps {

    WebDriver driver = CommonSteps.driver;

    @When("^a thing happens$")
    public void a_thing_happens() {
        driver.get("http://google.com");
    }
}

Since I know that beforeScenario() will always be called before each test, and that method is in the CommonSteps file, I declare it as a class variable there, and create a local variable at the top of other step classes to use in those steps. But since I'm just now learning java, is there a better way to do this? I am trying to adhere to best practices and make this as user friendly and scalable as possible. Thanks!

kroe761
  • 3,296
  • 9
  • 52
  • 81
  • 3
    If it needs to be scalable, don't make the `driver` `static`. What you need is dependency injection. Take the `driver` as a parameter in the constructor, or in a setter. See [this question](http://stackoverflow.com/q/3334578/5743988) and [this question](http://stackoverflow.com/q/21218868/5743988). – 4castle Dec 27 '16 at 00:59
  • Also [this question](https://stackoverflow.com/questions/31573676/sharing-same-selenium-webdriver-between-step-definition-files/31579738#31579738) could help you – troig Dec 27 '16 at 08:23
  • Also this (Di & Cucumber): https://stackoverflow.com/questions/33713674/what-is-the-best-way-to-pass-information-from-one-steps-def-class-to-another – Marit Jan 05 '18 at 18:05

0 Answers0