Watch the Lesson

The text version of this lesson is given in the following:

What Is a Parameterized Test?

A parameterized test is a test case that is invoked by using a predefined input and expected output. These tests are typically used to test classes that have no external dependencies and that provide methods which have no side effects.

Let’s move on and take a look at the system under test.

Introduction to System Under Test

During this lesson we will write unit tests for a simple Calculator class. It has one method called sum() and this method returns the sum of two integers. The source code of the Calculator class looks as follows:

Second, we have to create a static method that returns a Collection of Object arrays, and annotate this method with the @Parameters annotation. This method creates the input provided to the tested object and describes the expected output.

After we have created this method, the source code of our test class looks as follows:

Fourth, we have to write a constructor that takes the input and output data as constructor arguments. These arguments are provided by the custom test runner which obtains them by invoking the data() method. This constructor also creates the tested object.

After we have created this constructor, the source code of our test class looks as follows:

As we can see, JUnitParams solves the problems which we found from the parameterized tests that use the test runner provided by JUnit. It has no boilerplate code, and because the parameters are passed directly to the test method, we can have multiple test methods that use different parameters. We can even add normal test methods into our test class.

Also, one additional benefit of using JUnitParams is that we can implement custom data providers and read input data from external data sources such as CSV files.