Parameterize Browser

One of the greatest strengths of Selenium we talk about is cross browser testing i.e. the same script can run on multiple versions of browsers without code change. Of course we should tell the script which browser we need to run at the minimum – though that is called a configuration parameter. In this section, let’s see how we can parameterize the browser value and at run time decide which browser we want to kick off.

Pre-requisites:

  1. You have completed the section “Set up Env” and have your environment ready with JDK, maven and IntelliJ
  2. You have read and understood HTML DOM
  3. You downloaded the project code base for class9 under – https://github.com/machzqcq/CucumberJVMExamples and imported into IntelliJ and the structure should look as below

class9_project_structure

If imported into eclipse, it looks as below

class9_eclipse_project_structure

Hooks.java

In the @Before cucumber annotation method, we instantiate the driver. So this is the place where we need to bake the logic that creates the driver based on the browser value.

Setting Browser value through Maven

I would like to set the browser value through maven property on command line. Hence when we run “mvn -DBROWSER=<value> test” , the System property BROWSER has the value of browser we specify. I also read the environment variable BROWSER if Maven property is null.

Read the Browser value

The Hooks.java file now looks as below with all the logic inside. Since I wanted to have the flexibility to specify browser both from command line and through Maven Cucumber runner, I had the browser string first read from Maven properties, if that is null, then I read the environment property BROWSER. If that is null as well, I default to “chrome”

That is it! Rest all of the code we have been using since Class 1 through Class 9 remains the same. We just have to modify Hooks.java

How to Execute

Method 1 (From command line)

class9_cmd_execute

Method 1 (From IntelliJ)

First pull down Tools – Edit configuration. Then Add an environment variable BROWSER and specify its value {firefox, chrome, ie…}. The steps are below

class9_intellij_edit_configuration

class9_intellij_add_env

After this point, whenever you right click and run the scenario , it is going to pick up the browser

class9_run_scenario