You might be knowing everyone is suggesting to avoid hardcoding strings inside code like browser url, username, password, environment, which browser etc.
So to avoid hard coding, we use external file sources like json, xml or properties file to have all these values in key value pair.
so any one who want to run the tests, they can just the values in these external files and no need to visit the actual code.
This above works well when we want to run our tests manually from the code editor itself.
Problem –
But with increasing no. of tests, we tend to use nightly run using Azure devops or jenkins etc., where each run we can’t customise the values as we need to change the code base accordingly and push the code back to git or some other tool.
Solution –
So we need to provide a way where user can have the privilege to send the values from the command line itself [which the CI CD pipelines support to run the tests]
In this post, we will see what changes we need to do at code level to accept these parameter values from command line, so our tests will run accordingly.
Prerequisites –
- Maven project > pom.xml > sure-fire plugin
- TestNG
We can use String browser = System.getProperty("browser", "chrome");
From the above line, “chrome” is the default if not sending any value from command line.
If you want to change the value from command line, then you can use below –
mvn test -Dbrowser=firefox
Then the browser variable will become firefox
Let’s see usage of this above code line in selenium –
package testNgLearning; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class MavenParams { //mvn test -Dtest=testNgLearning.MavenParams -Dbrowser=firefox @Test public void MavenParamTest() throws InterruptedException { WebDriver driver = null; String browser = System.getProperty("browser", "chrome"); if(browser.contains("chrome")){ System.setProperty("webdriver.chrome.driver","/Users/skpatro/sel/chromedriver"); driver = new ChromeDriver(); }else if(browser.contains("firefox")){ System.setProperty("webdriver.gecko.driver","/Users/skpatro/sel/geckodriver"); driver = new FirefoxDriver(); } if(driver != null){ driver.get("https://qavbox.github.io/demo/links/"); Thread.sleep(2000); driver.quit(); } } }
If you run the above code from editor window, it will open the url in chrome browser as that’s the default browser we set.
To run a different browser name, we can use below command in command prompt or terminal
Navigate to current project directory and enter –
mvn test -Dtest=testNgLearning.MavenParams -Dbrowser=firefox
This above command will run MavenParams class in firefox browser.
As this is demo test, we have kept the variables in the same test class, in real time we can have a separate class only holding all the variables we need to send from maven command line, then we can access these variables from any test methods.
Hope this helps!