Parameterized junit test case with example

The “Parameterized Test” means vary parameter value for unit test. In JUnit, both @RunWith and @Parameter annotation are used 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;
@RunWith(Parameterized.class)
public class FibonacciTest { @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 },{ 6, 8 } }); } private int fInput; private int fExpected; public FibonacciTest(int input, int expected) { fInput = input; fExpected = expected; } @Test public void test() { assertEquals(fExpected, Fibonacci.compute(fInput)); } }
Each instance of FibonacciTest will be constructed using the two-argument constructor and the data values in the @Parameters method.
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.

No comments:

Post a Comment