|
| 1 | +package com.iluwatar.bloc; |
| 2 | +import org.junit.jupiter.api.BeforeEach; |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | +import java.util.concurrent.atomic.AtomicInteger; |
| 5 | +import static org.junit.jupiter.api.Assertions.*; |
| 6 | + |
| 7 | +class BlocTest { |
| 8 | + private Bloc bloc; |
| 9 | + private AtomicInteger stateValue; |
| 10 | + @BeforeEach |
| 11 | + void setUp() { |
| 12 | + bloc = new Bloc(); |
| 13 | + stateValue = new AtomicInteger(0); |
| 14 | + } |
| 15 | + @Test |
| 16 | + void initialState() { |
| 17 | + assertTrue(bloc.getListeners().isEmpty(), "No listeners should be present initially."); |
| 18 | + } |
| 19 | + |
| 20 | + @Test |
| 21 | + void IncrementUpdateState() { |
| 22 | + bloc.addListener(state -> stateValue.set(state.getValue())); |
| 23 | + bloc.increment(); |
| 24 | + assertEquals(1, stateValue.get(), "State should increment to 1"); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + void DecrementUpdateState() { |
| 29 | + bloc.addListener(state -> stateValue.set(state.getValue())); |
| 30 | + bloc.decrement(); |
| 31 | + assertEquals(-1, stateValue.get(), "State should decrement to -1"); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + void addingListener() { |
| 36 | + bloc.addListener(state -> {}); |
| 37 | + assertEquals(1, bloc.getListeners().size(), "Listener count should be 1."); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + void removingListener() { |
| 42 | + StateListener<State> listener = state -> {}; |
| 43 | + bloc.addListener(listener); |
| 44 | + bloc.removeListener(listener); |
| 45 | + assertTrue(bloc.getListeners().isEmpty(), "Listener count should be 0 after removal."); |
| 46 | + } |
| 47 | + @Test |
| 48 | + void multipleListeners() { |
| 49 | + AtomicInteger secondValue = new AtomicInteger(); |
| 50 | + bloc.addListener(state -> stateValue.set(state.getValue())); |
| 51 | + bloc.addListener(state -> secondValue.set(state.getValue())); |
| 52 | + bloc.increment(); |
| 53 | + assertEquals(1, stateValue.get(), "First listener should receive state 1."); |
| 54 | + assertEquals(1, secondValue.get(), "Second listener should receive state 1."); |
| 55 | + } |
| 56 | +} |
0 commit comments