JUnit @ParameterizedTest with @EnumSource

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 with @EnumSource 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

The @ParameterizedTest annotation marks methods that should be executed multiple times with different parameters. The @EnumSource annotation is used to provide a list of enum values to the parameterized test.

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 Enum and Class to be Tested

Create an enum and a Java class with methods that you want to test. For example, an Operation enum and a simple Calculator class:

public enum Operation {
    ADD, SUBTRACT, MULTIPLY, DIVIDE
}

public class Calculator {
    public int calculate(int a, int b, Operation operation) {
        switch (operation) {
            case ADD:
                return a + b;
            case SUBTRACT:
                return a - b;
            case MULTIPLY:
                return a * b;
            case DIVIDE:
                if (b == 0) {
                    throw new IllegalArgumentException("Cannot divide by zero");
                }
                return a / b;
            default:
                throw new UnsupportedOperationException("Unknown operation: " + operation);
        }
    }
}

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 @EnumSource.

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

public class CalculatorTest {
    private final Calculator calculator = new Calculator();

    @ParameterizedTest
    @EnumSource(Operation.class)
    void testCalculate(Operation operation) {
        int a = 6;
        int b = 2;
        int expected;
        
        switch (operation) {
            case ADD:
                expected = a + b;
                break;
            case SUBTRACT:
                expected = a - b;
                break;
            case MULTIPLY:
                expected = a * b;
                break;
            case DIVIDE:
                expected = a / b;
                break;
            default:
                throw new UnsupportedOperationException("Unknown operation: " + operation);
        }
        
        assertEquals(expected, calculator.calculate(a, b, operation), "Calculation should be correct for " + operation);
    }
}

In this example, the testCalculate method is annotated with @ParameterizedTest and uses @EnumSource to provide the list of Operation enum values. The test method will be executed once for each enum value.

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

Real-World Use Case

In real-world applications, enums are often used to represent fixed sets of constants, such as operations, states, or types. Using @EnumSource allows you to test methods with all possible values of an enum.

Create the Enum and Class to be Tested

Create an enum and a Java class that contains business logic. For example, a DayOfWeek enum and a Scheduler class that checks if a given day is a weekend:

public enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Scheduler {
    public boolean isWeekend(DayOfWeek day) {
        return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;
    }
}

In this class, the isWeekend method checks if a given day is a weekend.

Create the Parameterized Test Class

Create a test class for the Scheduler in the src/test/java directory. Use the @ParameterizedTest annotation and @EnumSource to provide different DayOfWeek enum values:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import static org.junit.jupiter.api.Assertions.*;

public class SchedulerTest {
    private final Scheduler scheduler = new Scheduler();

    @ParameterizedTest
    @EnumSource(value = DayOfWeek.class, names = {"SATURDAY", "SUNDAY"})
    void testIsWeekend(DayOfWeek day) {
        assertTrue(scheduler.isWeekend(day), day + " should be a weekend");
    }

    @ParameterizedTest
    @EnumSource(value = DayOfWeek.class, names = {"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"})
    void testIsNotWeekend(DayOfWeek day) {
        assertFalse(scheduler.isWeekend(day), day + " should not be a weekend");
    }
}

In this test class, the testIsWeekend method is annotated with @ParameterizedTest and uses @EnumSource to provide weekend DayOfWeek enum values. The testIsNotWeekend method provides weekday DayOfWeek enum values. The test methods will be executed once for each enum value.

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 with @EnumSource, you can ensure that your methods behave correctly with all possible values of an enum.

Leave a Comment

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

Scroll to Top