0
0
JUnittesting~3 mins

Why @EnumSource for enum values in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one test could cover every possible enum value without extra code?

The Scenario

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.

The Problem

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.

The Solution

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

Before vs After
Before
void testAdmin() { /* test for ADMIN */ }
void testUser() { /* test for USER */ }
void testGuest() { /* test for GUEST */ }
After
@ParameterizedTest
@EnumSource(UserRole.class)
void testRoles(UserRole role) { /* test for role */ }
What It Enables

You can easily test all enum cases with one simple test, making your tests faster, cleaner, and less error-prone.

Real Life Example

When your app adds a new user role, your tests automatically include it without extra work, ensuring no role is left untested.

Key Takeaways

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.