From a4ca964a03bce65f0b6162d54cbdefff41c68051 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 7 Oct 2017 13:58:39 +0200 Subject: [PATCH] mockito exceptions --- .../MockitoExceptionIntegrationTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java new file mode 100644 index 0000000000..9a25ccb28c --- /dev/null +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java @@ -0,0 +1,57 @@ +package org.baeldung.mockito; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.mockito.Mockito; + +public class MockitoExceptionIntegrationTest { + + @Test(expected = NullPointerException.class) + public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); + + dictMock.getMeaning("word"); + } + + @Test(expected = IllegalStateException.class) + public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + doThrow(IllegalStateException.class).when(dictMock) + .add(anyString(), anyString()); + + dictMock.add("word", "meaning"); + } + + @Test(expected = NullPointerException.class) + public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); + + dictMock.getMeaning("word"); + } + + @Test(expected = IllegalStateException.class) + public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + doThrow(new IllegalStateException("Error occurred")).when(dictMock) + .add(anyString(), anyString()); + + dictMock.add("word", "meaning"); + } + + // ===== + + @Test(expected = NullPointerException.class) + public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { + MyDictionary dict = new MyDictionary(); + MyDictionary spy = Mockito.spy(dict); + + when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); + spy.getMeaning("word"); + } +}