|
| 1 | +package org.baeldung.mockito; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | +import org.junit.runner.RunWith; |
| 5 | +import static org.junit.Assert.assertEquals; |
| 6 | + |
| 7 | +import static org.mockito.Mockito.*; |
| 8 | +import org.mockito.ArgumentCaptor; |
| 9 | +import static org.mockito.Matchers.any; |
| 10 | +import org.mockito.stubbing.Answer; |
| 11 | +import org.mockito.runners.MockitoJUnitRunner; |
| 12 | + |
| 13 | +@RunWith(MockitoJUnitRunner.class) |
| 14 | +public class MockitoVoidMethodsTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void whenAddCalledVerified() { |
| 18 | + MyList mockVoid = mock(MyList.class); |
| 19 | + mockVoid.add(0, ""); |
| 20 | + verify(mockVoid, times(1)).add(0, ""); |
| 21 | + } |
| 22 | + |
| 23 | + @Test(expected = Exception.class) |
| 24 | + public void givenNull_addThrows() { |
| 25 | + MyList mockVoid = mock(MyList.class); |
| 26 | + doThrow().when(mockVoid).add(isA(Integer.class), isNull()); |
| 27 | + mockVoid.add(0, null); |
| 28 | + } |
| 29 | + |
| 30 | + @Test |
| 31 | + public void whenAddCalledValueCaptured() { |
| 32 | + MyList mockVoid = mock(MyList.class); |
| 33 | + ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class); |
| 34 | + doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture()); |
| 35 | + mockVoid.add(0, "captured"); |
| 36 | + assertEquals("captured", valueCapture.getValue()); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + public void whenAddCalledAnswered() { |
| 41 | + MyList mockVoid = mock(MyList.class); |
| 42 | + doAnswer((Answer<Void>) invocation -> { |
| 43 | + Object arg0 = invocation.getArgument(0); |
| 44 | + Object arg1 = invocation.getArgument(1); |
| 45 | + |
| 46 | + //do something with the arguments here |
| 47 | + assertEquals(3, arg0); |
| 48 | + assertEquals("answer me", arg1); |
| 49 | + |
| 50 | + return null; |
| 51 | + }).when(mockVoid).add(any(Integer.class), any(String.class)); |
| 52 | + mockVoid.add(3, "answer me"); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + public void whenAddCalledRealMethodCalled() { |
| 57 | + MyList mockVoid = mock(MyList.class); |
| 58 | + doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class)); |
| 59 | + mockVoid.add(1, "real"); |
| 60 | + verify(mockVoid, times(1)).add(1, "real"); |
| 61 | + } |
| 62 | +} |
0 commit comments