TestNG provides a way to get the data from external sources like from excel/textfile/arrays which helps to prepare data driven framework in automation.
@Parameters – pass parameters from the testNG.xml
@dataProvider – Pass the parameters as a 2D array.
reference – https://testng.org/doc/documentation-main.html#parameters
In this post we will look into the testNG @Parameters
Let’s see the code implementation
@Parameters
package annotationpkg; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class parameters { @Test @Parameters({"browser", "url"}) public void parameterTest(String browserName,String browserUrl) { System.out.println("Browser used : " + browserName); System.out.println("url under test : " + browserUrl); } }
and the testng.xml looks like:
<xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="MySuite" parallel="none"> <test name="MyTest1"> <parameter name="browser" value="chrome"/> <parameter name="url" value="https://qavbox.github.io/demo"/> <classes> <class name="annotationpkg.parameters"/> </classes> </test> </suite>
As you can see above testng.xml, we have 3 parameter tags to pass to our method parameterTest(), and the method accepts as @parameters(…)
Parameters can be of data type like integer, character, string, boolean etc.
If you change the testng.xml file to below [don’t pass one parameter from the testng.xml], then we will get exception –
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" > <suite name="Suite1" verbose="1" > <test name="Regression1" > <!--parameter name="browser" value="firefox"/--> <parameter name="url" value="https://qavbox.github.io/demo"/> <classes> <class name="testNgLearning.parameter.SampleParameterTest"/> </classes> <test> <suite>
Output –
[Utils] [ERROR] [Error] org.testng.TestNGException:
Parameter 'browser' is required by @Test on method d_report but has not been marked @Optional or defined
To avoid this above error, either we will need to uncomment the browser parameter, or we need to use Optional keyword
public class parameters { @Test @Parameters({"browser", "url"}) public void parameterTest(@Optional("chrome") String browserName,String browserUrl) { System.out.println("Browser used : " + browserName); System.out.println("url under test : " + browserUrl); } }
This above code will first check for the browser in testng.xml, if it’s not found then the default value it will take as chrome [@Optional(“chrome”) String browserName]
Now you can run above tesng.xml to get the output as
Browser used : chrome url under test : https://qavbox.github.io/demo
Hope this helps!