What if one test could cover every possible enum value without extra code?
Why @EnumSource for enum values in JUnit? - Purpose & Use Cases
Imagine you have a list of different user roles in your app, like ADMIN, USER, and GUEST. You want to test your login system for each role manually by writing separate test cases for each one.
Writing separate tests for each enum value is slow and boring. You might forget a role or make mistakes copying similar code. It's hard to keep tests updated when roles change.
@EnumSource lets you run the same test automatically for every enum value. You write one test method, and JUnit runs it for ADMIN, USER, GUEST, and any new roles added later. This saves time and avoids errors.
void testAdmin() { /* test for ADMIN */ }
void testUser() { /* test for USER */ }
void testGuest() { /* test for GUEST */ }@ParameterizedTest @EnumSource(UserRole.class) void testRoles(UserRole role) { /* test for role */ }
You can easily test all enum cases with one simple test, making your tests faster, cleaner, and less error-prone.
When your app adds a new user role, your tests automatically include it without extra work, ensuring no role is left untested.
Manual tests for each enum value are repetitive and error-prone.
@EnumSource runs one test for all enum values automatically.
This keeps tests simple, complete, and easy to maintain.