JAVA-12032 Move Mockito ebook articles code to common module - mockito-simple- Delete mockito-3 since it had only 1 article which was moved to mockito-simple
This commit is contained in:
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.app.rest;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import com.baeldung.app.api.Flower;
|
||||
import com.baeldung.domain.service.FlowerService;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class FlowerControllerUnitTest {
|
||||
|
||||
@Mock
|
||||
private FlowerService flowerService;
|
||||
|
||||
@InjectMocks
|
||||
private FlowerController flowerController;
|
||||
|
||||
@Test
|
||||
public void isAFlower_withMockito_OK() {
|
||||
when(flowerService.analize(eq("violetta"))).thenReturn("Flower");
|
||||
|
||||
String response = flowerController.isAFlower("violetta");
|
||||
|
||||
Assert.assertEquals("Flower", response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isABigFlower_withMockito_OK() {
|
||||
when(flowerService.isABigFlower(eq("violetta"), anyInt())).thenReturn(true);
|
||||
|
||||
Flower flower = new Flower("violetta", 15);
|
||||
|
||||
Boolean response = flowerController.isABigFlower(flower);
|
||||
|
||||
Assert.assertTrue(response);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.app.rest;
|
||||
|
||||
import static org.mockito.Mockito.times;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import com.baeldung.app.api.MessageApi;
|
||||
import com.baeldung.domain.model.Message;
|
||||
import com.baeldung.domain.service.MessageService;
|
||||
import com.baeldung.domain.util.MessageMatcher;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MessageControllerUnitTest {
|
||||
|
||||
@Mock
|
||||
private MessageService messageService;
|
||||
|
||||
@InjectMocks
|
||||
private MessageController messageController;
|
||||
|
||||
@Test
|
||||
public void createMessage_NewMessage_OK() {
|
||||
MessageApi messageApi = new MessageApi();
|
||||
messageApi.setFrom("me");
|
||||
messageApi.setTo("you");
|
||||
messageApi.setText("Hello, you!");
|
||||
|
||||
messageController.createMessage(messageApi);
|
||||
|
||||
Message message = new Message();
|
||||
message.setFrom("me");
|
||||
message.setTo("you");
|
||||
message.setText("Hello, you!");
|
||||
|
||||
Mockito.verify(messageService, times(1)).deliverMessage(ArgumentMatchers.argThat(new MessageMatcher(message)));
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.domain.util;
|
||||
|
||||
import com.baeldung.domain.model.Message;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
|
||||
public class MessageMatcher implements ArgumentMatcher<Message> {
|
||||
|
||||
private Message left;
|
||||
|
||||
public MessageMatcher(Message message) {
|
||||
this.left = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(Message right) {
|
||||
return left.getFrom().equals(right.getFrom()) &&
|
||||
left.getTo().equals(right.getTo()) &&
|
||||
left.getText().equals(right.getText()) &&
|
||||
right.getDate() != null &&
|
||||
right.getId() != null;
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.junit5.mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import com.baeldung.junit5.mockito.repository.MailClient;
|
||||
import com.baeldung.junit5.mockito.repository.SettingRepository;
|
||||
import com.baeldung.junit5.mockito.repository.UserRepository;
|
||||
import com.baeldung.junit5.mockito.service.DefaultUserService;
|
||||
import com.baeldung.junit5.mockito.service.Errors;
|
||||
import com.baeldung.junit5.mockito.service.UserService;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class UserServiceUnitTest {
|
||||
|
||||
UserService userService;
|
||||
SettingRepository settingRepository;
|
||||
@Mock UserRepository userRepository;
|
||||
@Mock MailClient mailClient;
|
||||
|
||||
User user;
|
||||
|
||||
@BeforeEach
|
||||
void init(@Mock SettingRepository settingRepository) {
|
||||
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
||||
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
|
||||
when(settingRepository.getUserNameMinLength()).thenReturn(4);
|
||||
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);
|
||||
this.settingRepository = settingRepository;
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
|
||||
// Given
|
||||
user = new User("Jerry", 12);
|
||||
when(userRepository.insert(any(User.class))).then(new Answer<User>() {
|
||||
int sequence = 1;
|
||||
|
||||
@Override
|
||||
public User answer(InvocationOnMock invocation) throws Throwable {
|
||||
User user = (User) invocation.getArgument(0);
|
||||
user.setId(sequence++);
|
||||
return user;
|
||||
}
|
||||
});
|
||||
|
||||
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
||||
|
||||
// When
|
||||
User insertedUser = userService.register(user);
|
||||
|
||||
// Then
|
||||
verify(userRepository).insert(user);
|
||||
Assertions.assertNotNull(user.getId());
|
||||
verify(mailClient).sendUserRegistrationMail(insertedUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
|
||||
// Given
|
||||
user = new User("tom", 12);
|
||||
|
||||
// When
|
||||
try {
|
||||
userService.register(user);
|
||||
fail("Should give an error");
|
||||
} catch(Exception ex) {
|
||||
assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT);
|
||||
}
|
||||
|
||||
// Then
|
||||
verify(userRepository, never()).insert(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSmallAge_whenSaveUser_thenGiveYoungUserError() {
|
||||
// Given
|
||||
user = new User("jerry", 3);
|
||||
|
||||
// When
|
||||
try {
|
||||
userService.register(user);
|
||||
fail("Should give an error");
|
||||
} catch(Exception ex) {
|
||||
assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG);
|
||||
}
|
||||
|
||||
// Then
|
||||
verify(userRepository, never()).insert(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
|
||||
// Given
|
||||
user = new User("jerry", 12);
|
||||
Mockito.reset(userRepository);
|
||||
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
|
||||
|
||||
// When
|
||||
try {
|
||||
userService.register(user);
|
||||
fail("Should give an error");
|
||||
} catch(Exception ex) {
|
||||
assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE);
|
||||
}
|
||||
|
||||
// Then
|
||||
verify(userRepository, never()).insert(user);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
public final class FinalList extends MyList {
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MockFinals {
|
||||
|
||||
@Test
|
||||
public void whenMockFinalClassMockWorks() {
|
||||
|
||||
FinalList finalList = new FinalList();
|
||||
|
||||
FinalList mock = mock(FinalList.class);
|
||||
when(mock.size()).thenReturn(2);
|
||||
|
||||
assertNotEquals(mock.size(), finalList.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMockFinalMethodMockWorks() {
|
||||
|
||||
MyList myList = new MyList();
|
||||
|
||||
MyList mock = mock(MyList.class);
|
||||
when(mock.finalMethod()).thenReturn(1);
|
||||
|
||||
assertNotEquals(mock.finalMethod(), myList.finalMethod());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.baeldung.mockito.MyList;
|
||||
|
||||
public class MockFinalsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenMockFinalClassMockWorks() {
|
||||
|
||||
FinalList finalList = new FinalList();
|
||||
|
||||
FinalList mock = mock(FinalList.class);
|
||||
when(mock.size()).thenReturn(2);
|
||||
|
||||
assertNotEquals(mock.size(), finalList.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMockFinalMethodMockWorks() {
|
||||
|
||||
MyList myList = new MyList();
|
||||
|
||||
MyList mock = mock(MyList.class);
|
||||
when(mock.finalMethod()).thenReturn(1);
|
||||
|
||||
assertNotEquals(mock.finalMethod(), myList.finalMethod());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
//@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoAnnotationUnitTest {
|
||||
|
||||
@Mock
|
||||
private List<String> mockedList;
|
||||
|
||||
@Spy
|
||||
private List<String> spiedList = new ArrayList<>();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenNotUseMockAnnotation_thenCorrect() {
|
||||
final List<String> mockList = Mockito.mock(List.class);
|
||||
mockList.add("one");
|
||||
Mockito.verify(mockList).add("one");
|
||||
assertEquals(0, mockList.size());
|
||||
|
||||
Mockito.when(mockList.size()).thenReturn(100);
|
||||
assertEquals(100, mockList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseMockAnnotation_thenMockIsInjected() {
|
||||
mockedList.add("one");
|
||||
Mockito.verify(mockedList).add("one");
|
||||
assertEquals(0, mockedList.size());
|
||||
|
||||
Mockito.when(mockedList.size()).thenReturn(100);
|
||||
assertEquals(100, mockedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotUseSpyAnnotation_thenCorrect() {
|
||||
final List<String> spyList = Mockito.spy(new ArrayList<String>());
|
||||
spyList.add("one");
|
||||
spyList.add("two");
|
||||
|
||||
Mockito.verify(spyList).add("one");
|
||||
Mockito.verify(spyList).add("two");
|
||||
|
||||
assertEquals(2, spyList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spyList).size();
|
||||
assertEquals(100, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
|
||||
spiedList.add("one");
|
||||
spiedList.add("two");
|
||||
|
||||
Mockito.verify(spiedList).add("one");
|
||||
Mockito.verify(spiedList).add("two");
|
||||
|
||||
assertEquals(2, spiedList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spiedList).size();
|
||||
assertEquals(100, spiedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotUseCaptorAnnotation_thenCorrect() {
|
||||
final List<String> mockList = Mockito.mock(List.class);
|
||||
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
|
||||
mockList.add("one");
|
||||
Mockito.verify(mockList).add(arg.capture());
|
||||
|
||||
assertEquals("one", arg.getValue());
|
||||
}
|
||||
|
||||
@Captor
|
||||
private
|
||||
ArgumentCaptor<String> argCaptor;
|
||||
|
||||
@Test
|
||||
public void whenUseCaptorAnnotation_thenTheSam() {
|
||||
mockedList.add("one");
|
||||
Mockito.verify(mockedList).add(argCaptor.capture());
|
||||
|
||||
assertEquals("one", argCaptor.getValue());
|
||||
}
|
||||
|
||||
@Mock
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
@InjectMocks
|
||||
private MyDictionary dic = new MyDictionary();
|
||||
|
||||
@Test
|
||||
public void whenUseInjectMocksAnnotation_thenCorrect() {
|
||||
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||
|
||||
assertEquals("aMeaning", dic.getMeaning("aWord"));
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MockitoAnnotationsUninitializedUnitTest {
|
||||
|
||||
@Mock
|
||||
List<String> mockedList;
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
|
||||
Mockito.when(mockedList.size()).thenReturn(1);
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import com.baeldung.mockito.MyList;
|
||||
|
||||
public class MockitoConfigExamplesUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
|
||||
final boolean added = listMock.add(randomAlphabetic(6));
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
doReturn(false).when(listMock).add(anyString());
|
||||
|
||||
final boolean added = listMock.add(randomAlphabetic(6));
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
|
||||
|
||||
listMock.add(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
doThrow(NullPointerException.class).when(listMock).clear();
|
||||
|
||||
listMock.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
|
||||
|
||||
listMock.add(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
@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
|
||||
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.size()).thenCallRealMethod();
|
||||
|
||||
assertThat(listMock.size(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
|
||||
|
||||
final String element = listMock.get(1);
|
||||
assertThat(element, is(equalTo("Always the same")));
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.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 MockitoExceptionUnitTest {
|
||||
|
||||
@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");
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoRule;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MockitoInitWithMockitoJUnitRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public MockitoRule initRule = MockitoJUnit.rule();
|
||||
|
||||
@Mock
|
||||
private List<String> mockedList;
|
||||
|
||||
@Test
|
||||
public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
|
||||
when(mockedList.size()).thenReturn(41);
|
||||
|
||||
assertThat(mockedList.size()).isEqualTo(41);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoInjectIntoSpyUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
spyDic = Mockito.spy(new MyDictionary(wordMap));
|
||||
}
|
||||
|
||||
@Mock
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
@InjectMocks
|
||||
private MyDictionary dic = new MyDictionary();
|
||||
|
||||
private MyDictionary spyDic;
|
||||
|
||||
@Test
|
||||
public void whenUseInjectMocksAnnotation_thenCorrect() {
|
||||
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||
|
||||
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.MockSettings;
|
||||
import org.mockito.exceptions.verification.TooFewActualInvocations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class MockitoMockIntegrationTest {
|
||||
|
||||
private static class CustomAnswer implements Answer<Boolean> {
|
||||
@Override
|
||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void whenUsingSimpleMock_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithName_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, "myMock");
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
listMock.add(randomAlphabetic(6));
|
||||
|
||||
thrown.expect(TooFewActualInvocations.class);
|
||||
thrown.expectMessage(containsString("myMock.add"));
|
||||
|
||||
verify(listMock, times(2)).add(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithAnswer_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, new CustomAnswer());
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithSettings_thenCorrect() {
|
||||
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
||||
MyList listMock = mock(MyList.class, customSettings);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.MockSettings;
|
||||
import org.mockito.exceptions.verification.TooFewActualInvocations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class MockitoMockUnitTest {
|
||||
|
||||
private static class CustomAnswer implements Answer<Boolean> {
|
||||
@Override
|
||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void whenUsingSimpleMock_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithName_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, "myMock");
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
listMock.add(randomAlphabetic(6));
|
||||
|
||||
thrown.expect(TooFewActualInvocations.class);
|
||||
thrown.expectMessage(containsString("myMock.add"));
|
||||
|
||||
verify(listMock, times(2)).add(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithAnswer_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, new CustomAnswer());
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithSettings_thenCorrect() {
|
||||
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
||||
MyList listMock = mock(MyList.class, customSettings);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.exceptions.verification.NoInteractionsWanted;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class MockitoVerifyExamplesUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
verify(mockedList).size();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
verify(mockedList, times(1)).size();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
verifyNoInteractions(mockedList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
verify(mockedList, times(0)).size();
|
||||
}
|
||||
|
||||
@Test(expected = NoInteractionsWanted.class)
|
||||
public final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
mockedList.clear();
|
||||
|
||||
verify(mockedList).size();
|
||||
verifyNoMoreInteractions(mockedList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingOrderOfInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
mockedList.add("a parameter");
|
||||
mockedList.clear();
|
||||
|
||||
final InOrder inOrder = Mockito.inOrder(mockedList);
|
||||
inOrder.verify(mockedList).size();
|
||||
inOrder.verify(mockedList).add("a parameter");
|
||||
inOrder.verify(mockedList).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
|
||||
verify(mockedList, never()).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.clear();
|
||||
mockedList.clear();
|
||||
mockedList.clear();
|
||||
|
||||
verify(mockedList, atLeast(1)).clear();
|
||||
verify(mockedList, atMost(10)).clear();
|
||||
}
|
||||
|
||||
// with arguments
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.add("test");
|
||||
|
||||
verify(mockedList).add("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.add("test");
|
||||
|
||||
verify(mockedList).add(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.addAll(Lists.<String>newArrayList("someElement"));
|
||||
final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(mockedList).addAll(argumentCaptor.capture());
|
||||
final List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
|
||||
assertThat(capturedArgument, hasItem("someElement"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
class MyDictionary {
|
||||
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
MyDictionary() {
|
||||
wordMap = new HashMap<>();
|
||||
}
|
||||
|
||||
MyDictionary(Map<String, String> wordMap) {
|
||||
this.wordMap = wordMap;
|
||||
}
|
||||
|
||||
public void add(final String word, final String meaning) {
|
||||
wordMap.put(word, meaning);
|
||||
}
|
||||
|
||||
String getMeaning(final String word) {
|
||||
return wordMap.get(word);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import java.util.AbstractList;
|
||||
|
||||
public class MyList extends AbstractList<String> {
|
||||
|
||||
@Override
|
||||
public String get(final int index) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int index, String element) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
final public int finalMethod() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class EmailServiceUnitTest {
|
||||
|
||||
@Mock
|
||||
DeliveryPlatform platform;
|
||||
|
||||
@InjectMocks
|
||||
EmailService emailService;
|
||||
|
||||
@Captor
|
||||
ArgumentCaptor<Email> emailCaptor;
|
||||
|
||||
@Captor
|
||||
ArgumentCaptor<Credentials> credentialsCaptor;
|
||||
|
||||
@Test
|
||||
public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
|
||||
String to = "info@baeldung.com";
|
||||
String subject = "Using ArgumentCaptor";
|
||||
String body = "Hey, let'use ArgumentCaptor";
|
||||
|
||||
emailService.send(to, subject, body, false);
|
||||
|
||||
Mockito.verify(platform).deliver(emailCaptor.capture());
|
||||
Email emailCaptorValue = emailCaptor.getValue();
|
||||
assertEquals(Format.TEXT_ONLY, emailCaptorValue.getFormat());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDoesSupportHtml_expectHTMLEmailFormat() {
|
||||
String to = "info@baeldung.com";
|
||||
String subject = "Using ArgumentCaptor";
|
||||
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
|
||||
|
||||
emailService.send(to, subject, body, true);
|
||||
|
||||
Mockito.verify(platform).deliver(emailCaptor.capture());
|
||||
Email value = emailCaptor.getValue();
|
||||
assertEquals(Format.HTML, value.getFormat());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceRunning_expectUpResponse() {
|
||||
Mockito.when(platform.getServiceStatus()).thenReturn("OK");
|
||||
|
||||
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
||||
|
||||
assertEquals(ServiceStatus.UP, serviceStatus);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceNotRunning_expectDownResponse() {
|
||||
Mockito.when(platform.getServiceStatus()).thenReturn("Error");
|
||||
|
||||
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
||||
|
||||
assertEquals(ServiceStatus.DOWN, serviceStatus);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
|
||||
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
||||
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
||||
|
||||
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
|
||||
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
||||
Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
||||
|
||||
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
||||
assertEquals(credentials, credentialsCaptor.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotAuthenticated_expectFalse() {
|
||||
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
|
||||
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
|
||||
|
||||
assertFalse(emailService.authenticatedSuccessfully(credentials));
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.mockito.mockedstatic;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
class MockedStaticUnitTest {
|
||||
|
||||
@Test
|
||||
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
|
||||
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
||||
|
||||
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
|
||||
utilities.when(StaticUtils::name).thenReturn("Eugen");
|
||||
assertThat(StaticUtils.name()).isEqualTo("Eugen");
|
||||
}
|
||||
|
||||
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
|
||||
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
||||
|
||||
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
|
||||
utilities.when(() -> StaticUtils.range(2, 6))
|
||||
.thenReturn(Arrays.asList(10, 11, 12));
|
||||
|
||||
assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12);
|
||||
}
|
||||
|
||||
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.mockito.spy;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.exceptions.misusing.NotAMockException;
|
||||
import org.mockito.internal.progress.ThreadSafeMockingProgress;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
public class MockitoMisusingUnitTest {
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
ThreadSafeMockingProgress.mockingProgress().reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
|
||||
try {
|
||||
List<String> list = new ArrayList<String>();
|
||||
|
||||
Mockito.doReturn(100, Mockito.withSettings().lenient())
|
||||
.when(list)
|
||||
.size();
|
||||
|
||||
fail("Should have thrown a NotAMockException because 'list' is not a mock!");
|
||||
} catch (NotAMockException e) {
|
||||
assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.mockito.spy;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoSpyUnitTest {
|
||||
|
||||
@Spy
|
||||
private List<String> aSpyList = new ArrayList<String>();
|
||||
|
||||
@Test
|
||||
public void whenSpyingOnList_thenCorrect() {
|
||||
final List<String> list = new ArrayList<String>();
|
||||
final List<String> spyList = Mockito.spy(list);
|
||||
|
||||
spyList.add("one");
|
||||
spyList.add("two");
|
||||
|
||||
Mockito.verify(spyList).add("one");
|
||||
Mockito.verify(spyList).add("two");
|
||||
|
||||
assertEquals(2, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
|
||||
aSpyList.add("one");
|
||||
aSpyList.add("two");
|
||||
|
||||
Mockito.verify(aSpyList).add("one");
|
||||
Mockito.verify(aSpyList).add("two");
|
||||
|
||||
assertEquals(2, aSpyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStubASpy_thenStubbed() {
|
||||
final List<String> list = new ArrayList<String>();
|
||||
final List<String> spyList = Mockito.spy(list);
|
||||
|
||||
assertEquals(0, spyList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spyList).size();
|
||||
assertEquals(100, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMock_thenCreated() {
|
||||
final List<String> mockedList = Mockito.mock(ArrayList.class);
|
||||
|
||||
mockedList.add("one");
|
||||
Mockito.verify(mockedList).add("one");
|
||||
|
||||
assertEquals(0, mockedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateSpy_thenCreate() {
|
||||
final List<String> spyList = Mockito.spy(new ArrayList<String>());
|
||||
|
||||
spyList.add("one");
|
||||
Mockito.verify(spyList).add("one");
|
||||
|
||||
assertEquals(1, spyList.size());
|
||||
}
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.mockito.voidmethods;
|
||||
|
||||
import com.baeldung.mockito.MyList;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoVoidMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddCalledVerified() {
|
||||
MyList myList = mock(MyList.class);
|
||||
myList.add(0, "");
|
||||
|
||||
verify(myList, times(1)).add(0, "");
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenNull_addThrows() {
|
||||
MyList myList = mock(MyList.class);
|
||||
doThrow().when(myList).add(isA(Integer.class), isNull());
|
||||
|
||||
myList.add(0, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddCalledValueCaptured() {
|
||||
MyList myList = mock(MyList.class);
|
||||
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
|
||||
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
|
||||
myList.add(0, "captured");
|
||||
|
||||
assertEquals("captured", valueCapture.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddCalledAnswered() {
|
||||
MyList myList = mock(MyList.class);
|
||||
doAnswer(invocation -> {
|
||||
Object arg0 = invocation.getArgument(0);
|
||||
Object arg1 = invocation.getArgument(1);
|
||||
|
||||
//do something with the arguments here
|
||||
assertEquals(3, arg0);
|
||||
assertEquals("answer me", arg1);
|
||||
return null;
|
||||
}).when(myList).add(any(Integer.class), any(String.class));
|
||||
myList.add(3, "answer me");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddCalledRealMethodCalled() {
|
||||
MyList myList = mock(MyList.class);
|
||||
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
|
||||
myList.add(1, "real");
|
||||
|
||||
verify(myList, times(1)).add(1, "real");
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
mock-maker-inline
|
||||
Reference in New Issue
Block a user