JUnit 4 Tutorial 6 – Parameterized Test
The “Parameterized Test” means vary parameter value for unit test. In JUnit, both @RunWith and @Parameter annotation are use to provide parameter value for unit test, @Parameters have to return List[], and the parameter will pass into class constructor as argument.
import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * JUnit Parameterized Test * @author mkyong * */ @RunWith(value = Parameterized.class) public class JunitTest6 { private int number; public JunitTest6(int number) { this.number = number; } @Parameters public static Collection<Object[]> data() { Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } }; return Arrays.asList(data); } @Test public void pushTest() { System.out.println("Parameterized Number is : " + number); } }
Result
Parameterized Number is : 1 Parameterized Number is : 2 Parameterized Number is : 3 Parameterized Number is : 4
It has many limitations here; you have to follow the “JUnit” way to declare the parameter, and the parameter has to pass into constructor in order to initialize the class member as parameter value for testing. The return type of parameter class is “List []”, data type has been limited to String or primitive value.
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
How do you make it jdk 1.5 (or above) compliance? I’m getting: The expression of type List needs unchecked conversion to conform to Collection
I’m using jdk1.6, has no warning at the above code.
May be you can explicit convert the List to collection by using the following code,
@Parameters
public static Collection
Did you use tTestNG before? Personally i more prefer to use TestNG as my unit test framework.
http://www.mkyong.com/unittest/junit-4-vs-testng-comparison/