0
0
JUnittesting~15 mins

@EnumSource for enum values in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify method behavior for all enum values using @EnumSource
Preconditions (2)
Step 1: Create a parameterized test using JUnit 5
Step 2: Use @EnumSource to supply all Color enum values to the test method
Step 3: For each enum value, call isPrimaryColor with the enum value
Step 4: Verify the returned boolean matches expected: true for RED and BLUE, false for GREEN
✅ Expected Result: The test passes for all enum values, correctly asserting the method behavior
Automation Requirements - JUnit 5
Assertions Needed:
AssertTrue or AssertFalse depending on enum value
Best Practices:
Use @ParameterizedTest with @EnumSource for enum values
Use descriptive test method names
Keep test logic simple and clear
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

public class ColorTest {

    enum Color {
        RED, GREEN, BLUE
    }

    boolean isPrimaryColor(Color color) {
        return color == Color.RED || color == Color.BLUE;
    }

    @ParameterizedTest(name = "Test isPrimaryColor with {0}")
    @EnumSource(Color.class)
    void testIsPrimaryColor(Color color) {
        boolean expected = (color == Color.RED || color == Color.BLUE);
        assertEquals(expected, isPrimaryColor(color));
    }
}

This test class defines an enum Color with three values.

The method isPrimaryColor returns true only for RED and BLUE.

The test method testIsPrimaryColor is a parameterized test using @EnumSource(Color.class) to run once for each enum value.

Inside the test, it calculates the expected result and asserts that the method returns the correct boolean.

This approach ensures all enum values are tested automatically without writing separate tests for each.

Common Mistakes - 3 Pitfalls
Not using @EnumSource and manually listing enum values
Using incorrect assertion methods like asserttrue without condition
Not importing necessary JUnit 5 packages
Bonus Challenge

Now add a test that uses @EnumSource with names to test only RED and BLUE enum values

Show Hint