I don't think the solution presented by Sanjeev is particularly good. There is no reason couple your tests with your browsers. Tests should be browser agnostic. Imagine the mess you will have to have Chrome tests, Firefox tests, Safari tests, and then platform tests such as Samsung browser for mobile, etc.
The solution I created for my project resolves the browser (and associated driver) as well as the test environment by using runtime arguments passed through the Maven options.
To process these runtime parameters, I used Cucumber's @BeforeClass hook to initialize the driver and set the test environment based on the passed arguments. This hook must be used in a static method in your TestRunner class; otherwise it will not work. @BeforeClass executes before the @Before hook which it is used to call the setup for each scenario declared on the tests you're running.
My solution looks something like this:
@RunWith(Cucumber.class)
@CucumberOptions(
features= {"features"},
glue="stepDefinition"
,plugin= {"..."}
,dryRun = false
,tags= {"@MyTests"}
)
public class TestRunner {
@BeforeClass
public static void setup() throws Exception {
String browser = System.getProperty("browser");
String env = System.getProperty("myEnvironment");
WebDriver driver = TestUtils.initializeDriver(browser);
}
}
"browser": You don't have to define "browser" as a system property. All you do is pass the value as a runtime argument in the Maven options. I will show you how later.
"myEnvironment": There is no such system property. Therefore, you must define it somewhere. Since you are using Maven, you can define this property in the POM under the maven-surefire-plugin configuration node. This is how you do this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<includes/>
<systemPropertyVariables>
<environment>${myEnvironment}</environment>
</systemPropertyVariables>
</configuration>
</plugin>
Now, to pass the parameters, you will add the following to your Maven options:
-Dbrowser=chrome -DmyEnvironment=dev
The beauty of this approach is that you can define many custom properties on your POM and use the "-D" option to pass them to your program dynamically.
Lastly, initialize the driver. my "initializeDriver" method simply takes the String and looks up the path to the driver that I have stored in a config file. For example, if I pass "chrome" as argument as shown above, in the method I do the following:
if ("chrome".equals(key)) {
System.setProperty("webdriver.chrome.driver", path);
return new ChromeDriver();
} else if ...
The returned WebDriver I then store in a utility class that holds the driver that is used throughout my tests.
When I am running my tests from an IDE, such as Eclipse, I add the Maven options to the VM Arguments. Therefore, I can run @MyTests with any browser and environment combination.