|
| 1 | +package org.baeldung.mockito.service; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | +import static org.junit.Assert.assertNull; |
| 5 | +import static org.mockito.ArgumentMatchers.any; |
| 6 | +import static org.mockito.ArgumentMatchers.anyString; |
| 7 | +import static org.mockito.Mockito.doAnswer; |
| 8 | +import static org.mockito.Mockito.verify; |
| 9 | + |
| 10 | +import org.junit.Before; |
| 11 | +import org.junit.Test; |
| 12 | +import org.mockito.ArgumentCaptor; |
| 13 | +import org.mockito.Captor; |
| 14 | +import org.mockito.Mock; |
| 15 | +import org.mockito.MockitoAnnotations; |
| 16 | +import org.mockito.stubbing.Answer; |
| 17 | + |
| 18 | +public class ActionHandlerUnitTest { |
| 19 | + |
| 20 | + @Mock |
| 21 | + private Service service; |
| 22 | + |
| 23 | + @Captor |
| 24 | + private ArgumentCaptor<Callback<Response>> callbackCaptor; |
| 25 | + |
| 26 | + @Before |
| 27 | + public void setup() { |
| 28 | + MockitoAnnotations.initMocks(this); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void givenServiceWithValidResponse_whenCallbackReceived_thenProcessed() { |
| 33 | + ActionHandler handler = new ActionHandler(service); |
| 34 | + handler.doAction(); |
| 35 | + |
| 36 | + verify(service).doAction(anyString(), callbackCaptor.capture()); |
| 37 | + |
| 38 | + Callback<Response> callback = callbackCaptor.getValue(); |
| 39 | + Response response = new Response(); |
| 40 | + callback.reply(response); |
| 41 | + |
| 42 | + String expectedMessage = "Successful data response"; |
| 43 | + Data data = response.getData(); |
| 44 | + assertEquals("Should receive a successful message: ", expectedMessage, data.getMessage()); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + public void givenServiceWithInvalidResponse_whenCallbackReceived_thenNotProcessed() { |
| 49 | + Response response = new Response(); |
| 50 | + response.setIsValid(false); |
| 51 | + |
| 52 | + doAnswer((Answer<Void>) invocation -> { |
| 53 | + Callback<Response> callback = invocation.getArgument(1); |
| 54 | + callback.reply(response); |
| 55 | + |
| 56 | + Data data = response.getData(); |
| 57 | + assertNull("No data in invalid response: ", data); |
| 58 | + return null; |
| 59 | + }).when(service) |
| 60 | + .doAction(anyString(), any(Callback.class)); |
| 61 | + |
| 62 | + ActionHandler handler = new ActionHandler(service); |
| 63 | + handler.doAction(); |
| 64 | + } |
| 65 | +} |
0 commit comments