0
0
JUnittesting~10 mins

@EnumSource for enum values in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses JUnit's @EnumSource to run the same test method for each value of an enum. It verifies that the enum values are correctly passed and processed in the test.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import static org.junit.jupiter.api.Assertions.*;

public class TrafficLightTest {

    enum TrafficLight {
        RED, YELLOW, GREEN
    }

    @ParameterizedTest
    @EnumSource(TrafficLight.class)
    void testTrafficLightEnum(TrafficLight light) {
        assertNotNull(light);
        assertTrue(light == TrafficLight.RED || light == TrafficLight.YELLOW || light == TrafficLight.GREEN);
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test runner starts and identifies the parameterized test with @EnumSource for TrafficLight enumJUnit test environment ready to run tests-PASS
2Test method 'testTrafficLightEnum' runs with parameter TrafficLight.REDTest method executing with parameter REDassertNotNull(RED) and assertTrue(RED is one of RED, YELLOW, GREEN)PASS
3Test method 'testTrafficLightEnum' runs with parameter TrafficLight.YELLOWTest method executing with parameter YELLOWassertNotNull(YELLOW) and assertTrue(YELLOW is one of RED, YELLOW, GREEN)PASS
4Test method 'testTrafficLightEnum' runs with parameter TrafficLight.GREENTest method executing with parameter GREENassertNotNull(GREEN) and assertTrue(GREEN is one of RED, YELLOW, GREEN)PASS
5All enum values tested, test suite completesAll parameterized tests passed-PASS
Failure Scenario
Failing Condition: If the enum value passed to the test method is null or not one of the expected enum constants
Execution Trace Quiz - 3 Questions
Test your understanding
What does @EnumSource(TrafficLight.class) do in this test?
ARuns the test method only once with the first enum value
BRuns the test method once for each value in the TrafficLight enum
CSkips the test method for all enum values
DRuns the test method with random enum values
Key Result
Using @EnumSource in JUnit allows easy testing of all enum values without writing separate tests, ensuring full coverage of enum-related logic.