10. Passing “Optional” Parameters Through testng.xml and @Parameters annotation

Passing “Optional” Parameters Through testng.xml and @Parameters annotation

To pass optional parameters, use @Optional annotation.

package Others;

import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Parameters_Optional
{
    @Parameters({ "optional-value" })
    @Test
    public void optionTest(@Optional("optional value") String value) {
        System.out.println("This is: " + value);
    }
}
The preceding class file contains a single test method that takes one parameter as input. The said test method on execution prints the parameter value that is passed onto the console using the System.out.println method. The Parameter value is passed to the test method using the parameter named optional-value from the XML file. An optional value for the said parameter is defined using the @Optional annotation against the said parameter.

Testng.xml:
<suite name="Optional test Suite" verbose="1">
  <test name="Optional Test one">
    <classes>
      <class name="Others.Parameters_Optional" />
    </classes>
  </test>
  <test name="Optional Test two">
    <parameter name="optional-value" value="passed from xml" />
    <classes>
      <class name="Others.Parameters_Optional" />
    </classes>
  </test>
</suite>

In above test methods, the testng.xml file has two tests defined in it. No parameter is defined in the first test where as the second test declares a parameter named ‘optional-value‘ in it.

Output of running above testng.xml as test suite is :
This is: optional value
This is: passed from xml
===============================================
Optional test Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

2 comments:

  1. If we wants to pass multiple parameters as optional.Then how we can able to configure them in @Parameters() annotation.

    ReplyDelete
  2. I like your post very much. It is very much useful for my research. I hope you to share more info about this. Keep posting learn java online

    ReplyDelete