The parameterized functionality is very helpful when it comes to group repetitive code for different input data.
We can do the following if we wanted to inject a parameter from a config file:
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My parameterized test suite">
<test name="parameterised injection testing">
<parameter name="i" value="13"/>
<classes>
<class name="com.dimitrisli.testng.parameterized.ParameterizedInjectionTest" />
</classes>
</test>
</suite>
to a unit test:
package com.dimitrisli.testng.parameterized;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParameterizedInjectionTest {
@Test
@Parameters(value="i")
public void method1(int i){
System.out.println("inside method1() of parameterized example injected i = "+i);
}
}
@DataProvider is similar to JUnit 4′s @Parameters to inject values en masses, a trivial example would look like so:
package com.dimitrisli.testng.parameterized;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProviderTesting {
@DataProvider(name="dataProviderMethod")
public Object[][] parameterMethod(){
return new Object[][]{{"one",1},{"two",2}};
}
@Test(dataProvider="dataProviderMethod")
public void testMethod(String str, int val){
System.out.println("str="+str+", val="+val);
}
}
A nice variation is to pass proper Java beans around:
package com.dimitrisli.testng.parameterized;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class AdvancedParameterizedTesting {
public static class Bean{
private String val;
private int i;
public Bean(String val, int i){
this.val=val;
this.i=i;
}
public String getStr(){
return this.val;
}
public int getInt(){
return this.i;
}
}
@DataProvider(name = "advancedParameterizedMethod")
public Object[][] advancedParameterizedMethod(){
return new Object[][]{{new Bean("hi I am the bean",111)}};
}
@Test(dataProvider="advancedParameterizedMethod")
public void testMethod(Bean myBean){
System.out.println(myBean.getStr()+" "+myBean.getInt());
}
}
The source code could be found in this Github repository.
Pingback: (Unit) Testing Swiss Knife: All the Tools You Wanted to Know « The Holy Java