Java 13914 (#13083)

* [JAVA-13914] Replaced Junit4 annotations with Junit5

* [JAVA-13914] Replaced Junit4 annotations with Junit5

* [JAVA-13914] Fixed test

* [JAVA-13914] Clean up

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos 2022-12-08 14:17:51 +00:00 committed by GitHub
parent 205506f00a
commit 0264bb82c8
17 changed files with 307 additions and 242 deletions

View File

@ -1,6 +1,7 @@
package com.baeldung.app.rest; package com.baeldung.app.rest;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.AdditionalMatchers.or; import static org.mockito.AdditionalMatchers.or;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -10,18 +11,18 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.app.api.Flower; import com.baeldung.app.api.Flower;
import com.baeldung.domain.service.FlowerService; import com.baeldung.domain.service.FlowerService;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class FlowerControllerUnitTest { class FlowerControllerUnitTest {
@InjectMocks @InjectMocks
private FlowerController flowerController; private FlowerController flowerController;
@ -30,7 +31,7 @@ public class FlowerControllerUnitTest {
private FlowerService flowerService; private FlowerService flowerService;
@Test @Test
public void givenPoppyFlower_whenUsingDoReturn_thenCorrect() { void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
doReturn("Flower").when(flowerService).analyze("poppy"); doReturn("Flower").when(flowerService).analyze("poppy");
String response = flowerController.isAFlower("poppy"); String response = flowerController.isAFlower("poppy");
@ -38,25 +39,27 @@ public class FlowerControllerUnitTest {
} }
@Test @Test
public void givenAnyString_whenUsingArgumentMatcher_thenCorrect() { void givenAnyString_whenUsingArgumentMatcher_thenCorrect() {
when(flowerService.analyze(anyString())).thenReturn("Flower"); when(flowerService.analyze(anyString())).thenReturn("Flower");
String response = flowerController.isAFlower("violetta"); String response = flowerController.isAFlower("violetta");
assertThat(response).isEqualTo("Flower"); assertThat(response).isEqualTo("Flower");
} }
@Test(expected = InvalidUseOfMatchersException.class) @Test
public void whenIncorrectMatchers_thenThrowsError() { void whenIncorrectMatchers_thenThrowsError() {
when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true); assertThrows(InvalidUseOfMatchersException.class, () -> {
when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true);
});
Flower flower = new Flower("poppy", 15); Flower flower = new Flower("poppy", 15);
Boolean response = flowerController.isABigFlower(flower); Boolean response = flowerController.isABigFlower(flower);
assertThat(response).isTrue(); assertThat(response).isFalse();
} }
@Test @Test
public void whenCorrectMatchers_thenCorrect() { void whenCorrectMatchers_thenCorrect() {
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true); when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
Flower flower = new Flower("poppy", 15); Flower flower = new Flower("poppy", 15);
@ -65,23 +68,25 @@ public class FlowerControllerUnitTest {
assertThat(response).isTrue(); assertThat(response).isTrue();
} }
@Test(expected = InvalidUseOfMatchersException.class) @Test
public void whenUsingMatchersAsReturnValue_thenThrowsError() { void whenUsingMatchersAsReturnValue_thenThrowsError() {
flowerController.isAFlower("poppy"); flowerController.isAFlower("poppy");
String orMatcher = or(eq("poppy"), endsWith("y")); String orMatcher = or(eq("poppy"), endsWith("y"));
verify(flowerService).analyze(orMatcher); assertThrows(InvalidUseOfMatchersException.class, () -> {
verify(flowerService).analyze(orMatcher);
});
} }
@Test @Test
public void whenUsingMatchersAsOngoingStubbing_thenCorrect1() { void whenUsingMatchersAsOngoingStubbing_thenCorrect1() {
flowerController.isAFlower("poppy"); flowerController.isAFlower("poppy");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
} }
@Test @Test
public void whenUsingMatchersAsOngoingStubbing_thenCorrect2() { void whenUsingMatchersAsOngoingStubbing_thenCorrect2() {
flowerController.isAFlower("lily"); flowerController.isAFlower("lily");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));

View File

@ -5,52 +5,52 @@ import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.app.api.MessageDTO; import com.baeldung.app.api.MessageDTO;
import com.baeldung.domain.model.Message; import com.baeldung.domain.model.Message;
import com.baeldung.domain.service.MessageService; import com.baeldung.domain.service.MessageService;
import com.baeldung.domain.util.MessageMatcher; import com.baeldung.domain.util.MessageMatcher;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class MessageControllerUnitTest { class MessageControllerUnitTest {
@InjectMocks @InjectMocks
private MessageController messageController; private MessageController messageController;
@Mock @Mock
private MessageService messageService; private MessageService messageService;
@Test @Test
public void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO(); MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me"); messageDTO.setFrom("me");
messageDTO.setTo("you"); messageDTO.setTo("you");
messageDTO.setText("Hello, you!"); messageDTO.setText("Hello, you!");
messageController.createMessage(messageDTO); messageController.createMessage(messageDTO);
verify(messageService, times(1)).deliverMessage(any(Message.class)); verify(messageService, times(1)).deliverMessage(any(Message.class));
} }
@Test @Test
public void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO(); MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me"); messageDTO.setFrom("me");
messageDTO.setTo("you"); messageDTO.setTo("you");
messageDTO.setText("Hello, you!"); messageDTO.setText("Hello, you!");
messageController.createMessage(messageDTO); messageController.createMessage(messageDTO);
Message message = new Message(); Message message = new Message();
message.setFrom("me"); message.setFrom("me");
message.setTo("you"); message.setTo("you");
message.setText("Hello, you!"); message.setText("Hello, you!");
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
} }
} }

View File

@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -13,7 +14,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
@ -115,7 +115,7 @@ class UserServiceUnitTest {
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() { void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
// Given // Given
user = new User("jerry", 12); user = new User("jerry", 12);
Mockito.reset(userRepository); reset(userRepository);
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true); when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
// When // When

View File

@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class MockFinalsUnitTest { class MockFinalsUnitTest {
@Test @Test
public void whenMockFinalMethodMockWorks() { void whenMockFinalMethodMockWorks() {
MyList myList = new MyList(); MyList myList = new MyList();

View File

@ -1,23 +1,27 @@
package com.baeldung.mockito; package com.baeldung.mockito;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class MockitoAnnotationUnitTest { class MockitoAnnotationUnitTest {
@Mock @Mock
private List<String> mockedList; private List<String> mockedList;
@ -36,61 +40,61 @@ public class MockitoAnnotationUnitTest {
// tests // tests
@Test @Test
public void whenNotUseMockAnnotation_thenCorrect() { void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class); final List<String> mockList = mock(List.class);
mockList.add("one"); mockList.add("one");
Mockito.verify(mockList).add("one"); verify(mockList).add("one");
assertEquals(0, mockList.size()); assertEquals(0, mockList.size());
Mockito.when(mockList.size()).thenReturn(100); when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size()); assertEquals(100, mockList.size());
} }
@Test @Test
public void whenUseMockAnnotation_thenMockIsInjected() { void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one"); mockedList.add("one");
Mockito.verify(mockedList).add("one"); verify(mockedList).add("one");
assertEquals(0, mockedList.size()); assertEquals(0, mockedList.size());
Mockito.when(mockedList.size()).thenReturn(100); when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size()); assertEquals(100, mockedList.size());
} }
@Test @Test
public void whenNotUseSpyAnnotation_thenCorrect() { void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = Mockito.spy(new ArrayList<String>()); final List<String> spyList = spy(new ArrayList<String>());
spyList.add("one"); spyList.add("one");
spyList.add("two"); spyList.add("two");
Mockito.verify(spyList).add("one"); verify(spyList).add("one");
Mockito.verify(spyList).add("two"); verify(spyList).add("two");
assertEquals(2, spyList.size()); assertEquals(2, spyList.size());
Mockito.doReturn(100).when(spyList).size(); doReturn(100).when(spyList).size();
assertEquals(100, spyList.size()); assertEquals(100, spyList.size());
} }
@Test @Test
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one"); spiedList.add("one");
spiedList.add("two"); spiedList.add("two");
Mockito.verify(spiedList).add("one"); verify(spiedList).add("one");
Mockito.verify(spiedList).add("two"); verify(spiedList).add("two");
assertEquals(2, spiedList.size()); assertEquals(2, spiedList.size());
Mockito.doReturn(100).when(spiedList).size(); doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size()); assertEquals(100, spiedList.size());
} }
@Test @Test
public void whenNotUseCaptorAnnotation_thenCorrect() { void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class); final List<String> mockList = mock(List.class);
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class); final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one"); mockList.add("one");
Mockito.verify(mockList).add(arg.capture()); verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue()); assertEquals("one", arg.getValue());
} }
@ -100,9 +104,9 @@ public class MockitoAnnotationUnitTest {
ArgumentCaptor<String> argCaptor; ArgumentCaptor<String> argCaptor;
@Test @Test
public void whenUseCaptorAnnotation_thenTheSame() { void whenUseCaptorAnnotation_thenTheSame() {
mockedList.add("one"); mockedList.add("one");
Mockito.verify(mockedList).add(argCaptor.capture()); verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue()); assertEquals("one", argCaptor.getValue());
} }
@ -114,8 +118,8 @@ public class MockitoAnnotationUnitTest {
private MyDictionary dic = new MyDictionary(); private MyDictionary dic = new MyDictionary();
@Test @Test
public void whenUseInjectMocksAnnotation_thenCorrect() { void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", dic.getMeaning("aWord")); assertEquals("aMeaning", dic.getMeaning("aWord"));
} }

View File

@ -6,11 +6,13 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule; import org.mockito.junit.MockitoRule;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest { public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
@Rule @Rule
@ -23,6 +25,6 @@ public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
public void whenUsingMockitoJUnitRule_thenMocksInitialized() { public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
when(mockedList.size()).thenReturn(41); when(mockedList.size()).thenReturn(41);
assertThat(mockedList.size()).isEqualTo(41); assertThat(mockedList).hasSize(41);
} }
} }

View File

@ -1,22 +1,28 @@
package com.baeldung.mockito; package com.baeldung.mockito;
import org.junit.Before;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.runner.RunWith; import static org.mockito.Mockito.spy;
import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.when;
import org.mockito.*; import static org.mockito.MockitoAnnotations.openMocks;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class MockitoAnnotationsInjectIntoSpyUnitTest { class MockitoAnnotationsInjectIntoSpyUnitTest {
@Before @BeforeEach
public void init() { public void init() {
MockitoAnnotations.openMocks(this); openMocks(this);
spyDic = Mockito.spy(new MyDictionary(wordMap)); spyDic = spy(new MyDictionary(wordMap));
} }
@Mock @Mock
@ -28,8 +34,8 @@ public class MockitoAnnotationsInjectIntoSpyUnitTest {
private MyDictionary spyDic; private MyDictionary spyDic;
@Test @Test
public void whenUseInjectMocksAnnotation_thenCorrect() { void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", spyDic.getMeaning("aWord")); assertEquals("aMeaning", spyDic.getMeaning("aWord"));
} }

View File

@ -1,18 +1,23 @@
package com.baeldung.mockito; package com.baeldung.mockito;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import java.util.List; import java.util.List;
public class MockitoAnnotationsUninitializedUnitTest { class MockitoAnnotationsUninitializedUnitTest {
@Mock @Mock
List<String> mockedList; List<String> mockedList;
@Test(expected = NullPointerException.class) @Test
public void whenMockitoAnnotationsUninitialized_thenNPEThrown() { void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
Mockito.when(mockedList.size()).thenReturn(1); assertThrows(NullPointerException.class, () -> {
when(mockedList.size()).thenReturn(1);
});
} }
} }

View File

@ -1,57 +1,71 @@
package com.baeldung.mockito; package com.baeldung.mockito;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
public class MockitoExceptionUnitTest { @ExtendWith(MockitoExtension.class)
class MockitoExceptionUnitTest {
@Test(expected = NullPointerException.class) @Test
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class); MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
assertThrows(NullPointerException.class, () -> {
dictMock.getMeaning("word");
});
dictMock.getMeaning("word");
} }
@Test(expected = IllegalStateException.class) @Test
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() { void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class); MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock) doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString()); .add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> {
dictMock.add("word", "meaning");
});
dictMock.add("word", "meaning");
} }
@Test(expected = NullPointerException.class) @Test
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class); MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
assertThrows(NullPointerException.class, () -> {
dictMock.getMeaning("word");
});
dictMock.getMeaning("word");
} }
@Test(expected = IllegalStateException.class) @Test
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class); MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock) doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString()); .add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> {
dictMock.add("word", "meaning");
});
dictMock.add("word", "meaning");
} }
// ===== // =====
@Test(expected = NullPointerException.class) @Test
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary(); MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict); MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word"); assertThrows(NullPointerException.class, () -> {
spy.getMeaning("word");
});
} }
} }

View File

@ -10,16 +10,16 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings; import static org.mockito.Mockito.withSettings;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.MockSettings; import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooFewActualInvocations; import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
public class MockitoMockUnitTest { class MockitoMockUnitTest {
@Test @Test
public void whenUsingSimpleMock_thenCorrect() { void whenUsingSimpleMock_thenCorrect() {
MyList listMock = mock(MyList.class); MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false); when(listMock.add(anyString())).thenReturn(false);
boolean added = listMock.add(randomAlphabetic(6)); boolean added = listMock.add(randomAlphabetic(6));
@ -29,7 +29,7 @@ public class MockitoMockUnitTest {
} }
@Test @Test
public void whenUsingMockWithName_thenCorrect() { void whenUsingMockWithName_thenCorrect() {
MyList listMock = mock(MyList.class, "myMock"); MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false); when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6)); listMock.add(randomAlphabetic(6));
@ -47,7 +47,7 @@ public class MockitoMockUnitTest {
} }
@Test @Test
public void whenUsingMockWithAnswer_thenCorrect() { void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer()); MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6)); boolean added = listMock.add(randomAlphabetic(6));
@ -56,7 +56,7 @@ public class MockitoMockUnitTest {
} }
@Test @Test
public void whenUsingMockWithSettings_thenCorrect() { void whenUsingMockWithSettings_thenCorrect() {
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
MyList listMock = mock(MyList.class, customSettings); MyList listMock = mock(MyList.class, customSettings);
boolean added = listMock.add(randomAlphabetic(6)); boolean added = listMock.add(randomAlphabetic(6));

View File

@ -1,9 +1,11 @@
package com.baeldung.mockito; package com.baeldung.mockito;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -13,69 +15,71 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.InOrder; import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.NoInteractionsWanted;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
public class MockitoVerifyExamplesUnitTest { class MockitoVerifyExamplesUnitTest {
// tests // tests
@Test @Test
public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() { final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.size(); mockedList.size();
verify(mockedList).size(); verify(mockedList).size();
} }
@Test @Test
public final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() { final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.size(); mockedList.size();
verify(mockedList, times(1)).size(); verify(mockedList, times(1)).size();
} }
@Test @Test
public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() { final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
verifyNoInteractions(mockedList); verifyNoInteractions(mockedList);
} }
@Test @Test
public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() { final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size(); verify(mockedList, times(0)).size();
} }
@Test(expected = NoInteractionsWanted.class) @Test
public final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.size(); mockedList.size();
mockedList.clear(); mockedList.clear();
verify(mockedList).size(); verify(mockedList).size();
verifyNoMoreInteractions(mockedList); assertThrows(NoInteractionsWanted.class, () -> {
verifyNoMoreInteractions(mockedList);
});
} }
@Test @Test
public final void whenVerifyingOrderOfInteractions_thenCorrect() { final void whenVerifyingOrderOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.size(); mockedList.size();
mockedList.add("a parameter"); mockedList.add("a parameter");
mockedList.clear(); mockedList.clear();
final InOrder inOrder = Mockito.inOrder(mockedList); final InOrder inOrder = inOrder(mockedList);
inOrder.verify(mockedList).size(); inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter"); inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear(); inOrder.verify(mockedList).clear();
} }
@Test @Test
public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() { final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.size(); mockedList.size();
@ -83,7 +87,7 @@ public class MockitoVerifyExamplesUnitTest {
} }
@Test @Test
public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() { final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.clear(); mockedList.clear();
mockedList.clear(); mockedList.clear();
@ -96,7 +100,7 @@ public class MockitoVerifyExamplesUnitTest {
// with arguments // with arguments
@Test @Test
public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() { final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.add("test"); mockedList.add("test");
@ -104,7 +108,7 @@ public class MockitoVerifyExamplesUnitTest {
} }
@Test @Test
public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() { final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.add("test"); mockedList.add("test");
@ -112,7 +116,7 @@ public class MockitoVerifyExamplesUnitTest {
} }
@Test @Test
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class); final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String>newArrayList("someElement")); mockedList.addAll(Lists.<String>newArrayList("someElement"));

View File

@ -2,21 +2,24 @@ package com.baeldung.mockito;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class MockitoWhenThenExamplesUnitTest {
class MockitoWhenThenExamplesUnitTest {
@Test @Test
public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() { final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false); when(listMock.add(anyString())).thenReturn(false);
final boolean added = listMock.add(randomAlphabetic(6)); final boolean added = listMock.add(randomAlphabetic(6));
@ -24,67 +27,79 @@ public class MockitoWhenThenExamplesUnitTest {
} }
@Test @Test
public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() { final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
doReturn(false).when(listMock).add(anyString()); doReturn(false).when(listMock).add(anyString());
final boolean added = listMock.add(randomAlphabetic(6)); final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse(); assertThat(added).isFalse();
} }
@Test(expected = IllegalStateException.class) @Test
public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class); when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6)); assertThrows(IllegalStateException.class, () -> {
listMock.add(randomAlphabetic(6));
});
} }
@Test @Test
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6)); listMock.add(randomAlphabetic(6));
} }
@Test(expected = NullPointerException.class) @Test
public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() { final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear(); doThrow(NullPointerException.class).when(listMock).clear();
listMock.clear(); assertThrows(NullPointerException.class, () -> {
} listMock.clear();
});
@Test(expected = IllegalStateException.class)
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6));
}
@Test(expected = NullPointerException.class)
public final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
final MyList instance = new MyList();
final MyList spy = Mockito.spy(instance);
doThrow(NullPointerException.class).when(spy).size();
spy.size();
} }
@Test @Test
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
assertThrows(IllegalStateException.class, () -> {
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6));
});
}
@Test
final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
final MyList instance = new MyList();
final MyList spy = spy(instance);
doThrow(NullPointerException.class).when(spy).size();
assertThrows(NullPointerException.class, () -> {
spy.size();
});
}
@Test
final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
final MyList listMock = mock(MyList.class);
when(listMock.size()).thenCallRealMethod(); when(listMock.size()).thenCallRealMethod();
assertThat(listMock).hasSize(1); assertThat(listMock).hasSize(1);
} }
@Test @Test
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() { final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class); final MyList listMock = mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1); final String element = listMock.get(1);

View File

@ -3,18 +3,20 @@ package com.baeldung.mockito.argumentcaptor;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class EmailServiceUnitTest { class EmailServiceUnitTest {
@Mock @Mock
DeliveryPlatform platform; DeliveryPlatform platform;
@ -29,34 +31,34 @@ public class EmailServiceUnitTest {
ArgumentCaptor<Credentials> credentialsCaptor; ArgumentCaptor<Credentials> credentialsCaptor;
@Test @Test
public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
String to = "info@baeldung.com"; String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor"; String subject = "Using ArgumentCaptor";
String body = "Hey, let'use ArgumentCaptor"; String body = "Hey, let'use ArgumentCaptor";
emailService.send(to, subject, body, false); emailService.send(to, subject, body, false);
Mockito.verify(platform).deliver(emailCaptor.capture()); verify(platform).deliver(emailCaptor.capture());
Email emailCaptorValue = emailCaptor.getValue(); Email emailCaptorValue = emailCaptor.getValue();
assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY); assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY);
} }
@Test @Test
public void whenDoesSupportHtml_expectHTMLEmailFormat() { void whenDoesSupportHtml_expectHTMLEmailFormat() {
String to = "info@baeldung.com"; String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor"; String subject = "Using ArgumentCaptor";
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>"; String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
emailService.send(to, subject, body, true); emailService.send(to, subject, body, true);
Mockito.verify(platform).deliver(emailCaptor.capture()); verify(platform).deliver(emailCaptor.capture());
Email value = emailCaptor.getValue(); Email value = emailCaptor.getValue();
assertThat(value.getFormat()).isEqualTo(Format.HTML); assertThat(value.getFormat()).isEqualTo(Format.HTML);
} }
@Test @Test
public void whenServiceRunning_expectUpResponse() { void whenServiceRunning_expectUpResponse() {
Mockito.when(platform.getServiceStatus()).thenReturn("OK"); when(platform.getServiceStatus()).thenReturn("OK");
ServiceStatus serviceStatus = emailService.checkServiceStatus(); ServiceStatus serviceStatus = emailService.checkServiceStatus();
@ -64,8 +66,8 @@ public class EmailServiceUnitTest {
} }
@Test @Test
public void whenServiceNotRunning_expectDownResponse() { void whenServiceNotRunning_expectDownResponse() {
Mockito.when(platform.getServiceStatus()).thenReturn("Error"); when(platform.getServiceStatus()).thenReturn("Error");
ServiceStatus serviceStatus = emailService.checkServiceStatus(); ServiceStatus serviceStatus = emailService.checkServiceStatus();
@ -73,26 +75,26 @@ public class EmailServiceUnitTest {
} }
@Test @Test
public void whenUsingArgumentMatcherForValidCredentials_expectTrue() { void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
assertTrue(emailService.authenticatedSuccessfully(credentials)); assertTrue(emailService.authenticatedSuccessfully(credentials));
} }
@Test @Test
public void whenUsingArgumentCaptorForValidCredentials_expectTrue() { void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
assertTrue(emailService.authenticatedSuccessfully(credentials)); assertTrue(emailService.authenticatedSuccessfully(credentials));
assertThat(credentialsCaptor.getValue()).isEqualTo(credentials); assertThat(credentialsCaptor.getValue()).isEqualTo(credentials);
} }
@Test @Test
public void whenNotAuthenticated_expectFalse() { void whenNotAuthenticated_expectFalse() {
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
assertFalse(emailService.authenticatedSuccessfully(credentials)); assertFalse(emailService.authenticatedSuccessfully(credentials));
} }

View File

@ -2,9 +2,9 @@ package com.baeldung.mockito.mockedstatic;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mockStatic;
import java.util.Arrays; import java.util.Arrays;
@ -14,7 +14,7 @@ class MockedStaticUnitTest {
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
assertThat(StaticUtils.name()).isEqualTo("Baeldung"); assertThat(StaticUtils.name()).isEqualTo("Baeldung");
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) { try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
utilities.when(StaticUtils::name).thenReturn("Eugen"); utilities.when(StaticUtils::name).thenReturn("Eugen");
assertThat(StaticUtils.name()).isEqualTo("Eugen"); assertThat(StaticUtils.name()).isEqualTo("Eugen");
} }
@ -26,7 +26,7 @@ class MockedStaticUnitTest {
void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) { try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
utilities.when(() -> StaticUtils.range(2, 6)) utilities.when(() -> StaticUtils.range(2, 6))
.thenReturn(Arrays.asList(10, 11, 12)); .thenReturn(Arrays.asList(10, 11, 12));

View File

@ -2,29 +2,30 @@ package com.baeldung.mockito.spy;
import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.exceptions.misusing.NotAMockException;
public class MockitoMisusingMockOrSpyUnitTest { class MockitoMisusingMockOrSpyUnitTest {
@Test @Test
public void givenNotASpy_whenDoReturn_thenThrowNotAMock() { void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
assertThatThrownBy(() -> Mockito.doReturn(100).when(list).size()) assertThatThrownBy(() -> doReturn(100).when(list).size())
.isInstanceOf(NotAMockException.class) .isInstanceOf(NotAMockException.class)
.hasMessageContaining("Argument passed to when() is not a mock!"); .hasMessageContaining("Argument passed to when() is not a mock!");
} }
@Test @Test
public void givenASpy_whenDoReturn_thenNoError() { void givenASpy_whenDoReturn_thenNoError() {
final List<String> spyList = Mockito.spy(new ArrayList<>()); final List<String> spyList = spy(new ArrayList<>());
assertThatNoException().isThrownBy(() -> Mockito.doReturn(100).when(spyList).size()); assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());
} }
} }

View File

@ -1,30 +1,33 @@
package com.baeldung.mockito.spy; package com.baeldung.mockito.spy;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class MockitoSpyUnitTest { public class MockitoSpyUnitTest {
@Test @Test
public void whenSpyingOnList_thenCorrect() { void whenSpyingOnList_thenCorrect() {
final List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<String>();
final List<String> spyList = Mockito.spy(list); final List<String> spyList = spy(list);
spyList.add("one"); spyList.add("one");
spyList.add("two"); spyList.add("two");
Mockito.verify(spyList).add("one"); verify(spyList).add("one");
Mockito.verify(spyList).add("two"); verify(spyList).add("two");
assertThat(spyList).hasSize(2); assertThat(spyList).hasSize(2);
} }
@ -33,43 +36,43 @@ public class MockitoSpyUnitTest {
private List<String> aSpyList = new ArrayList<String>(); private List<String> aSpyList = new ArrayList<String>();
@Test @Test
public void whenUsingTheSpyAnnotation_thenObjectIsSpied() { void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
aSpyList.add("one"); aSpyList.add("one");
aSpyList.add("two"); aSpyList.add("two");
Mockito.verify(aSpyList).add("one"); verify(aSpyList).add("one");
Mockito.verify(aSpyList).add("two"); verify(aSpyList).add("two");
assertThat(aSpyList).hasSize(2); assertThat(aSpyList).hasSize(2);
} }
@Test @Test
public void whenStubASpy_thenStubbed() { void whenStubASpy_thenStubbed() {
final List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<String>();
final List<String> spyList = Mockito.spy(list); final List<String> spyList = spy(list);
assertEquals(0, spyList.size()); assertEquals(0, spyList.size());
Mockito.doReturn(100).when(spyList).size(); doReturn(100).when(spyList).size();
assertThat(spyList).hasSize(100); assertThat(spyList).hasSize(100);
} }
@Test @Test
public void whenCreateMock_thenCreated() { void whenCreateMock_thenCreated() {
final List<String> mockedList = Mockito.mock(ArrayList.class); final List<String> mockedList = mock(ArrayList.class);
mockedList.add("one"); mockedList.add("one");
Mockito.verify(mockedList).add("one"); verify(mockedList).add("one");
assertThat(mockedList).hasSize(0); assertThat(mockedList).hasSize(0);
} }
@Test @Test
public void whenCreateSpy_thenCreate() { void whenCreateSpy_thenCreate() {
final List<String> spyList = Mockito.spy(new ArrayList<>()); final List<String> spyList = spy(new ArrayList<>());
spyList.add("one"); spyList.add("one");
Mockito.verify(spyList).add("one"); verify(spyList).add("one");
assertThat(spyList).hasSize(1); assertThat(spyList).hasSize(1);
} }

View File

@ -1,6 +1,8 @@
package com.baeldung.mockito.voidmethods; package com.baeldung.mockito.voidmethods;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.isNull;
@ -12,34 +14,36 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.mockito.MyList; import com.baeldung.mockito.MyList;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class MockitoVoidMethodsUnitTest { class MockitoVoidMethodsUnitTest {
@Test @Test
public void whenAddCalledVerified() { void whenAddCalledVerified() {
MyList myList = mock(MyList.class); MyList myList = mock(MyList.class);
myList.add(0, ""); myList.add(0, "");
verify(myList, times(1)).add(0, ""); verify(myList, times(1)).add(0, "");
} }
@Test(expected = Exception.class) @Test
public void givenNull_addThrows() { void givenNull_addThrows() {
MyList myList = mock(MyList.class); MyList myList = mock(MyList.class);
doThrow().when(myList).add(isA(Integer.class), isNull()); assertThrows(Exception.class, () -> {
doThrow().when(myList).add(isA(Integer.class), isNull());
});
myList.add(0, null); myList.add(0, null);
} }
@Test @Test
public void whenAddCalledValueCaptured() { void whenAddCalledValueCaptured() {
MyList myList = mock(MyList.class); MyList myList = mock(MyList.class);
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
@ -49,7 +53,7 @@ public class MockitoVoidMethodsUnitTest {
} }
@Test @Test
public void whenAddCalledAnswered() { void whenAddCalledAnswered() {
MyList myList = mock(MyList.class); MyList myList = mock(MyList.class);
doAnswer(invocation -> { doAnswer(invocation -> {
Object arg0 = invocation.getArgument(0); Object arg0 = invocation.getArgument(0);
@ -64,7 +68,7 @@ public class MockitoVoidMethodsUnitTest {
} }
@Test @Test
public void whenAddCalledRealMethodCalled() { void whenAddCalledRealMethodCalled() {
MyList myList = mock(MyList.class); MyList myList = mock(MyList.class);
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class)); doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
myList.add(1, "real"); myList.add(1, "real");