TestNG Showcase – Parameterized Testing

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.

About these ads

One comment on “TestNG Showcase – Parameterized Testing

  1. Pingback: (Unit) Testing Swiss Knife: All the Tools You Wanted to Know « The Holy Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s