JUnit @ParameterizedTest Annotation

JUnit is a popular testing framework in the Java ecosystem that simplifies writing and running tests. The @ParameterizedTest annotation in JUnit is used to run the same test with different inputs. This guide covers the basics of using the @ParameterizedTest annotation to write parameterized tests in JUnit.

Table of Contents

  1. Introduction
  2. Steps to Create a JUnit Parameterized Test
  3. Real-World Use Case
  4. Conclusion

Introduction

JUnit provides an easy way to write and execute unit tests for Java applications. The @ParameterizedTest annotation marks methods that should be executed multiple times with different parameters. This is useful for testing a method with various inputs without writing multiple test cases.

Steps to Create a JUnit Parameterized Test

Step 1: Add Maven Dependency

To use JUnit in your project, you need to add the JUnit dependency to your pom.xml file. Use the latest version of JUnit 5:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

Step 2: Create the Class to be Tested

Create a Java class with methods that you want to test. For example, a simple MathUtils class:

public class MathUtils {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

Step 3: Create the Parameterized Test Class

Create a test class in the src/test/java directory. Use the @ParameterizedTest annotation and specify the source of the parameters using @ValueSource.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class MathUtilsTest {
    private final MathUtils mathUtils = new MathUtils();

    @ParameterizedTest
    @ValueSource(ints = {1, 2, 3, 4, 5})
    void testAddition(int number) {
        int result = mathUtils.add(number, 2);
        assertEquals(number + 2, result, () -> number + " + 2 should equal " + (number + 2));
    }
}

In this example, the testAddition method is annotated with @ParameterizedTest and uses @ValueSource to provide a list of integers. The test method will be executed once for each value in the list.

Step 4: Run the Test

You can run the test using your IDE, Maven, or Gradle.

Using an IDE:

Most IDEs, like IntelliJ IDEA and Eclipse, have built-in support for running JUnit tests. Simply right-click on your test class or method and select “Run.”

Using Maven:

If you’re using Maven, you can run your tests with the following command:

mvn test

Using Gradle:

If you’re using Gradle, you can run your tests with the following command:

gradle test

Annotations to Provide Input Date to @ParameterizedTest Annotation

Real-World Use Case

In real-world applications, you may need to test methods with various inputs. For instance, a StringUtils class might need to be tested with different string inputs to ensure correct behavior.

Create the Class to be Tested

Create a Java class that contains business logic. For example, a StringUtils class that checks if a string is a palindrome:

public class StringUtils {
    public boolean isPalindrome(String str) {
        if (str == null) {
            return false;
        }
        String cleaned = str.replaceAll("\\s+", "").toLowerCase();
        return cleaned.equals(new StringBuilder(cleaned).reverse().toString());
    }
}

In this class, the isPalindrome method checks if a given string is a palindrome.

Create the Parameterized Test Class

Create a test class for the StringUtils in the src/test/java directory. Use the @ParameterizedTest annotation and @CsvSource to provide different string inputs and expected results:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class StringUtilsTest {
    private final StringUtils stringUtils = new StringUtils();

    @ParameterizedTest
    @CsvSource({
        "madam, true",
        "racecar, true",
        "hello, false",
        "A man a plan a canal Panama, true",
        "'', true",
        "' ', true"
    })
    void testIsPalindrome(String input, boolean expected) {
        boolean result = stringUtils.isPalindrome(input);
        assertEquals(expected, result, () -> input + " should be " + expected);
    }
}

In this test class, the testIsPalindrome method is annotated with @ParameterizedTest and uses @CsvSource to provide different string inputs and their expected results. The test method will be executed once for each set of inputs and expected results.

Running the Tests

You can run the tests using your IDE, Maven, or Gradle.

Using an IDE:

Most IDEs, like IntelliJ IDEA and Eclipse, have built-in support for running JUnit tests. Simply right-click on your test class or method and select “Run.”

Using Maven:

If you’re using Maven, you can run your tests with the following command:

mvn test

Using Gradle:

If you’re using Gradle, you can run your tests with the following command:

gradle test

Conclusion

The @ParameterizedTest annotation in JUnit makes it easy to run the same test with different inputs. By using @ParameterizedTest, you can ensure that your methods behave correctly with various inputs without writing multiple test cases.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top