TestNG Optional Parameters
TestNG optional parameters option will provide optional values to a parameter, this value will be used if parameter value is not found or not provided in the xml configuration file. To achieve this we will use @Optional annotation in the test method as an argument.
Below is the sample code:
import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class OptionalParameterTest { @Parameters({"optional-value"}) @Test public void optionParameterTest(@Optional("Default Parameter, if no value from XML File") String value) { System.out.println("The Parameter is :" + value); } }
The above program contains a single method and that takes one parameter as an argument. In the previous blog (i.e.Parameterization using testng.xml file) we have seen the parameters annotation for parameterization.
Now will run the above program using testng.xml configuration file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Optional Parameter Suite"> <test name="Optional Parameter Test One"> <classes> <class name="OptionalParameterTest"></class> </classes> </test> <test name="Optional Parameter Test Two"> <parameter name="optional-value" value="Passed Parameter From XML File"></parameter> <classes> <class name="OptionalParameterTest"></class> </classes> </test> </suite>
Below is the output for the above program:
The above XML file contains two tests called Optional Parameter Test One, Optional Parameter Test Two. For Optional Parameter Test One we have not provided any argument as parameter from the XML file. So, while executing the test it took the optional parameter which is provided in the Test method using @Optional annotation.
For Optional Parameter Test Two, we provided the argument as parameter using Parameter tag in the XML file. So, while executing the test it took the value form the XML file instead the optional value which is provided in the Test.
Conclusion:
1.We can pass the parameters to the test method Two ways.
2.Can pass the parameter using xml file using parameter tag.
3.Can pass the parameter using @Optional annotation in the test method.
4.If NOT provided parameter from the xml file then it will take the optional parameter which is provided in the test method using @Optional annotation.
5.It provided the parameter value from the xml then it will consider this value.
6.The parameter value which is provided in the xml file take the high priority than the optional value and it will override the optional value in the execution.