JUnit Parameterized Test Example Tutorial

In this blog post, we will provide a simple example that will explain how to create a Parameterized test in JUnit with code examples. We will take an example of a addition, where a method adds two integers and returns an integer as an output. We will also discuss how to write test cases automatically for this method in JUnit by using the Parameterized.class. For those who are new to Parametrization, it is a runner inside JUnit that will run the same test case with different set of inputs.To get started with parametrized testing in JUnit, we have to have a Java class with a method that adds two numbers and returns an integer back to the calling method. My class file is "Addition.java" and the code for the file is provided below;
public class Addition {
    public int AddNumbers(int a, int b){
        int c = a + b;
        return c; 
    }
}
You can refer to the JUnit test case file for this example, after you have created and compiled this file. The test case class file will be called AdditionTestParametrized.java and the code for this file is provided below;
import static org.junit.Assert.assertEquals;
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;

@RunWith(Parameterized.class)
public class AdditionTestParametrized {

    private int expected; 
    private int firstNumber; 
    private int secondNumber; 

    @Parameters 
    public static Collection<Integer[]> getTestParameters() {
       return Arrays.asList(new Integer[][] {
          {2, 1, 1},  
          {3, 2, 1},  
          {4, 3, 1},  
       });
    }

    public AdditionTestParametrized(int expected, 
       int firstNumber, int secondNumber) {
       this.expected = expected;
       this.firstNumber = firstNumber;
       this.secondNumber = secondNumber;
    }

    @Test
    public void sum() {
       Addition instance = new Addition();     
       System.out.println("About to execute a test case with inputs " + firstNumber + " and " + secondNumber);
       assertEquals("Failed Test Case",expected, instance.AddNumbers(firstNumber, secondNumber));
    } 
}

Now, if you run the JUnit test against the test class, you will find that it gets executed thrice based on the inputs and the results are returned back to you on the screen. To run a test class with Parameterized test runner, you have to make sure that the following points are met;
1) You have to include a @RunWith annotation with the Parametrized class as its argument. (Refer to the code example above)
2) You have to provide a method annotated with @Parameters. This method will supply the input values for the test to be executed.
3) You must provide a method with @Test annotation, that will be invoked by JUnit for testing.
Try giving a run on this example and let us know if you are stuck somewhere.

No comments:

Post a Comment