|
| 1 | +package com.iluwatar; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.BeforeEach; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +import static org.mockito.Mockito.*; |
| 7 | + |
| 8 | +class TrafficLightFsmTest { |
| 9 | + |
| 10 | + private TrafficLightContext context; |
| 11 | + private TrafficLightState redState; |
| 12 | + private TrafficLightState greenState; |
| 13 | + private TrafficLightState yellowState; |
| 14 | + |
| 15 | + @BeforeEach |
| 16 | + void setUp() { |
| 17 | + // Set up the initial states for testing |
| 18 | + redState = mock(RedLightState.class); |
| 19 | + greenState = mock(GreenLightState.class); |
| 20 | + yellowState = mock(YellowLightState.class); |
| 21 | + |
| 22 | + // Initialize the context with the Red state |
| 23 | + context = new TrafficLightContext(redState); |
| 24 | + } |
| 25 | + |
| 26 | + @Test |
| 27 | + void testRedToGreenStateTransition() { |
| 28 | + // Mock the behavior of handleEvent for red state |
| 29 | + context.handleEvent(); // Expected transition to green state |
| 30 | + verify(redState).handleEvent(context); // Verify that handleEvent was called |
| 31 | + assert context.getCurrentState() instanceof GreenLightState; // Assert the next state is Green |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + void testGreenToYellowStateTransition() { |
| 36 | + // Change to green state manually |
| 37 | + context.setState(greenState); |
| 38 | + context.handleEvent(); // Expected transition to yellow state |
| 39 | + verify(greenState).handleEvent(context); // Verify the handleEvent for green state |
| 40 | + assert context.getCurrentState() instanceof YellowLightState; // Assert the next state is Yellow |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + void testYellowToRedStateTransition() { |
| 45 | + // Change to yellow state manually |
| 46 | + context.setState(yellowState); |
| 47 | + context.handleEvent(); // Expected transition to red state |
| 48 | + verify(yellowState).handleEvent(context); // Verify the handleEvent for yellow state |
| 49 | + assert context.getCurrentState() instanceof RedLightState; // Assert the next state is Red |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + void testStateTransitionOrder() { |
| 54 | + // Test the full cycle: Red -> Green -> Yellow -> Red |
| 55 | + context = new TrafficLightContext(new RedLightState()); |
| 56 | + |
| 57 | + // Red to Green |
| 58 | + context.handleEvent(); |
| 59 | + assert context.getCurrentState() instanceof GreenLightState; |
| 60 | + |
| 61 | + // Green to Yellow |
| 62 | + context.handleEvent(); |
| 63 | + assert context.getCurrentState() instanceof YellowLightState; |
| 64 | + |
| 65 | + // Yellow to Red |
| 66 | + context.handleEvent(); |
| 67 | + assert context.getCurrentState() instanceof RedLightState; |
| 68 | + } |
| 69 | +} |
| 70 | + |
0 commit comments