|
| 1 | +package org.baeldung.mockito; |
| 2 | + |
| 3 | +import static org.mockito.ArgumentMatchers.anyString; |
| 4 | +import static org.mockito.Mockito.doThrow; |
| 5 | +import static org.mockito.Mockito.mock; |
| 6 | +import static org.mockito.Mockito.when; |
| 7 | + |
| 8 | +import org.junit.Test; |
| 9 | +import org.mockito.Mockito; |
| 10 | + |
| 11 | +public class MockitoExceptionIntegrationTest { |
| 12 | + |
| 13 | + @Test(expected = NullPointerException.class) |
| 14 | + public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { |
| 15 | + MyDictionary dictMock = mock(MyDictionary.class); |
| 16 | + when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); |
| 17 | + |
| 18 | + dictMock.getMeaning("word"); |
| 19 | + } |
| 20 | + |
| 21 | + @Test(expected = IllegalStateException.class) |
| 22 | + public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() { |
| 23 | + MyDictionary dictMock = mock(MyDictionary.class); |
| 24 | + doThrow(IllegalStateException.class).when(dictMock) |
| 25 | + .add(anyString(), anyString()); |
| 26 | + |
| 27 | + dictMock.add("word", "meaning"); |
| 28 | + } |
| 29 | + |
| 30 | + @Test(expected = NullPointerException.class) |
| 31 | + public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { |
| 32 | + MyDictionary dictMock = mock(MyDictionary.class); |
| 33 | + when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); |
| 34 | + |
| 35 | + dictMock.getMeaning("word"); |
| 36 | + } |
| 37 | + |
| 38 | + @Test(expected = IllegalStateException.class) |
| 39 | + public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { |
| 40 | + MyDictionary dictMock = mock(MyDictionary.class); |
| 41 | + doThrow(new IllegalStateException("Error occurred")).when(dictMock) |
| 42 | + .add(anyString(), anyString()); |
| 43 | + |
| 44 | + dictMock.add("word", "meaning"); |
| 45 | + } |
| 46 | + |
| 47 | + // ===== |
| 48 | + |
| 49 | + @Test(expected = NullPointerException.class) |
| 50 | + public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { |
| 51 | + MyDictionary dict = new MyDictionary(); |
| 52 | + MyDictionary spy = Mockito.spy(dict); |
| 53 | + |
| 54 | + when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); |
| 55 | + spy.getMeaning("word"); |
| 56 | + } |
| 57 | +} |
0 commit comments