|
| 1 | +package org.baeldung.mockito; |
| 2 | + |
| 3 | +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; |
| 4 | +import static org.hamcrest.Matchers.is; |
| 5 | +import static org.junit.Assert.assertThat; |
| 6 | +import static org.mockito.Matchers.anyString; |
| 7 | +import static org.mockito.Mockito.doThrow; |
| 8 | +import static org.mockito.Mockito.when; |
| 9 | + |
| 10 | +import org.junit.Test; |
| 11 | +import org.mockito.Mockito; |
| 12 | + |
| 13 | +@SuppressWarnings("unchecked") |
| 14 | +public class MockitoConfigExamplesTest { |
| 15 | + |
| 16 | + // tests |
| 17 | + |
| 18 | + @Test |
| 19 | + public final void whenMockBehaviorIsConfigured_thenBehaviorIsVerified() { |
| 20 | + final MyList listMock = Mockito.mock(MyList.class); |
| 21 | + when(listMock.add(anyString())).thenReturn(false); |
| 22 | + |
| 23 | + final boolean added = listMock.add(randomAlphabetic(6)); |
| 24 | + assertThat(added, is(false)); |
| 25 | + } |
| 26 | + |
| 27 | + @Test(expected = IllegalStateException.class) |
| 28 | + public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { |
| 29 | + final MyList listMock = Mockito.mock(MyList.class); |
| 30 | + when(listMock.add(anyString())).thenThrow(IllegalStateException.class); |
| 31 | + |
| 32 | + listMock.add(randomAlphabetic(6)); |
| 33 | + } |
| 34 | + |
| 35 | + @Test(expected = NullPointerException.class) |
| 36 | + public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() { |
| 37 | + final MyList listMock = Mockito.mock(MyList.class); |
| 38 | + doThrow(NullPointerException.class).when(listMock).clear(); |
| 39 | + |
| 40 | + listMock.clear(); |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { |
| 45 | + final MyList listMock = Mockito.mock(MyList.class); |
| 46 | + when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); |
| 47 | + |
| 48 | + listMock.add(randomAlphabetic(6)); |
| 49 | + } |
| 50 | + |
| 51 | + @Test(expected = IllegalStateException.class) |
| 52 | + public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { |
| 53 | + final MyList listMock = Mockito.mock(MyList.class); |
| 54 | + when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); |
| 55 | + |
| 56 | + listMock.add(randomAlphabetic(6)); |
| 57 | + listMock.add(randomAlphabetic(6)); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments