0
0
JUnittesting~5 mins

@EnumSource for enum values in JUnit

Choose your learning style9 modes available
Introduction

@EnumSource helps run the same test with all values of an enum. This saves time and avoids writing many similar tests.

You want to check that a method works correctly for every value in an enum.
You have a list of fixed options and want to test each one automatically.
You want to avoid repeating similar test code for each enum value.
Syntax
JUnit
@ParameterizedTest
@EnumSource(EnumClassName.class)
void testMethod(EnumClassName value) {
    // test code using value
}

The test method receives each enum value one by one.

Use @EnumSource with the enum class name to specify which enum to use.

Examples
This test runs once for each Color enum value, checking it is not null.
JUnit
@ParameterizedTest
@EnumSource(Color.class)
void testColor(Color color) {
    assertNotNull(color);
}
This test runs only for SMALL and MEDIUM enum values of Size.
JUnit
@ParameterizedTest
@EnumSource(value = Size.class, names = {"SMALL", "MEDIUM"})
void testSize(Size size) {
    assertTrue(size == Size.SMALL || size == Size.MEDIUM);
}
Sample Program

This test runs three times, once for each day in the Day enum. It checks that the day value is not null.

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

enum Day {
    MONDAY, TUESDAY, WEDNESDAY
}

public class EnumSourceTest {

    @ParameterizedTest
    @EnumSource(Day.class)
    void testDayIsNotNull(Day day) {
        assertNotNull(day);
    }
}
OutputSuccess
Important Notes

You can filter enum values using the 'names' attribute in @EnumSource.

Use @EnumSource when you want to test all or some enum values without writing loops.

Summary

@EnumSource runs tests for each enum value automatically.

It helps test all fixed options easily and clearly.