Optional Annotation in TestNG

Optional Annotation in TestNG

As we know, we can pass parameter values to the test methods during run time from testng.xml file by specifying Parameters annotation to test method.

To do this, we need to declare parameters tag in xml file using ‘name’ and ‘value’ attribute. Where the name attribute of the tag defines name of the parameter and the value attribute defines the value of the parameter.

If defined parameter is not found in your testng.xml file, The test method will receive the default value which is specified inside the @Optional annotation.

Syntax to define Parameter:

<parameter name="param" value="Value of parameter" />

Syntax to define @Optional annotation

@Parameters("browser")
@Test
public void method1(@Optional("Optional Value") String value)
{ ... }

Example:

  1. package Annotations;
    import org.testng.annotations.Optional;
    import org.testng.annotations.Parameters;
    import org.testng.annotations.Test;
    public class OptionalParamExample  {
    
    	@Parameters("param one")@Test
    	public void method1(String p1)  {
    
    		System.out.println("Value passed ::"  + p1);
    	}
    
    	@Parameters("param two")@Test
    	public void method2(@Optional("I am Optional") String p2)  {
    
    		System.out.println("Value passed ::"  + p2);
    	}@Parameters("param three")@Test
    	public void method3(@Optional("I am Optional") String p3)  {
    
    		System.out.println("Value passed ::"  + p3);
    	}
    }

Below is the testng.xml where we will pass the parameters to test methods

  1. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
    <suite name="Sample Test Suite" verbose="1" >
    <parameter name="param one" value="First parameter" />
    <parameter name="param two" value="Second parameter" />
    <test name="Sample Test Cases" >
    <classes>
    <class name="Annotations.OptionalParamExample" />
    </classes>
    </test>
    </suite>

When we execute the above program the output should look like below.

[TestNG] Running:
  D:\WorkSpace\DemoTestNG\testng.xml
Value passed ::First parameter
Value passed ::Second parameter
Value passed ::I am Optional

===============================================
Sample Test Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================

 

Leave a Reply

Your email address will not be published. Required fields are marked *