Junit5 Parametrized Tests

 What are parameterized unit tests and How to write them using Junit5?

In this article we will learn about parameterized tests and how to write Junit parameterized tests. The parameterized tests is the concept of running a single test multiple times, but with different parameters and outcomes. The parameterized unit tests allow us to avoid writing same code multiple times.

JUnit 5, the newest version of JUnit, adds a slew of new capabilities to make creating developer tests easier.

Parameterized tests are one such feature. This feature allows us to repeat a test procedure with varied parameters many times.

To start writing parameterized tests, we first need to include `junit-jupiter-params` dependency in our project.

For Maven, add below dependency to the project's pom.xml file.


<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.7.0</version>
    <scope>test</scope>
</dependency>

Let's consider the following class, with a utility method to verify if an integer is odd number or not.

IntegerUtils.java

public final class IntegerUtils {

    public static boolean isOdd(int number) {
        return number % 2 != 0;
    }
}

We can write a simple unit test that will invoke the `isOdd()` method of the util class with various number of options and verify it's working.

Let's consider the following class, with a utility method to verify if an integer is odd number or not.

IntegerUtilsTest.java

class IntegerUtilsTest {

    @ParameterizedTest
    @ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE})
    void test_odd_numbers(int value) {
        Assertions.assertTrue(IntegerUtils.isOdd(value));
    }

    @ParameterizedTest
    @ValueSource(ints = {0, 2, 1000, -30, 150, (Integer.MAX_VALUE - 1)})
    void test_even_numbers(int value) {
        Assertions.assertFalse(IntegerUtils.isOdd(value));
    }
}

Above is a very simple example of how parameterization works in Junit5 framework.  In further articles, we will explore different variations of parameterized unit tests supported by Junit5 framework.

Full source code can be found in our Github Repository.


0 comments:

Post a Comment