JAVA-13721 Format, Fix Package, Upgrade version of all the articles

This commit is contained in:
Dhawal Kapil 2023-04-28 20:24:19 +05:30
parent b9f2acc923
commit 005c68e0a6
52 changed files with 1103 additions and 1103 deletions

View File

@ -29,12 +29,14 @@
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.mockito</groupId>
@ -55,9 +57,8 @@
</build>
<properties>
<spring-framework.version>5.3.20</spring-framework.version>
<!-- testing -->
<mockito.version>4.6.1</mockito.version>
<spring-framework.version>6.0.8</spring-framework.version>
<mockito.version>5.3.1</mockito.version>
</properties>
</project>

View File

@ -1,31 +0,0 @@
package com.baeldung.app.api;
public class MessageDTO {
private String from;
private String to;
private String text;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.app.rest;
import com.baeldung.app.api.Flower;
import com.baeldung.domain.service.FlowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/flowers")
public class FlowerController {
@Autowired
private FlowerService flowerService;
@PostMapping("/isAFlower")
public String isAFlower (@RequestBody String flower) {
return flowerService.analyze(flower);
}
@PostMapping("/isABigFlower")
public Boolean isABigFlower (@RequestBody Flower flower) {
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
}
}

View File

@ -1,34 +0,0 @@
package com.baeldung.app.rest;
import com.baeldung.app.api.MessageDTO;
import com.baeldung.domain.model.Message;
import com.baeldung.domain.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;
@Controller
@RequestMapping("/message")
public class MessageController {
@Autowired
private MessageService messageService;
@PostMapping
public Message createMessage (@RequestBody MessageDTO messageDTO) {
Message message = new Message();
message.setText(messageDTO.getText());
message.setFrom(messageDTO.getFrom());
message.setTo(messageDTO.getTo());
message.setDate(Date.from(Instant.now()));
message.setId(UUID.randomUUID());
return messageService.deliverMessage(message);
}
}

View File

@ -1,53 +0,0 @@
package com.baeldung.domain.model;
import java.util.Date;
import java.util.UUID;
public class Message {
private String from;
private String to;
private String text;
private Date date;
private UUID id;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
}

View File

@ -1,9 +0,0 @@
package com.baeldung.junit5.mockito.repository;
import com.baeldung.junit5.mockito.User;
public interface MailClient {
void sendUserRegistrationMail(User user);
}

View File

@ -1,9 +0,0 @@
package com.baeldung.junit5.mockito.service;
import com.baeldung.junit5.mockito.User;
public interface UserService {
User register(User user);
}

View File

@ -1,14 +1,25 @@
package com.baeldung.mockito.argumentcaptor;
public class Credentials {
private final String name;
private final String password;
private final String key;
private final String name;
private final String password;
private final String key;
public Credentials(String name, String password, String key) {
this.name = name;
this.password = password;
this.key = key;
}
public Credentials(String name, String password, String key) {
this.name = name;
this.password = password;
this.key = key;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public String getKey() {
return key;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.app.api;
package com.baeldung.mockito.argumentmatchers;
public class Flower {

View File

@ -0,0 +1,53 @@
package com.baeldung.mockito.argumentmatchers;
import java.util.Date;
import java.util.UUID;
public class Message {
private String from;
private String to;
private String text;
private Date date;
private UUID id;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.mockito.argumentmatchers;
public class MessageDTO {
private String from;
private String to;
private String text;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.mockito.argumentmatchers.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baeldung.mockito.argumentmatchers.Flower;
import com.baeldung.mockito.argumentmatchers.service.FlowerService;
@Controller
@RequestMapping("/flowers")
public class FlowerController {
@Autowired
private FlowerService flowerService;
@PostMapping("/isAFlower")
public String isAFlower(@RequestBody String flower) {
return flowerService.analyze(flower);
}
@PostMapping("/isABigFlower")
public Boolean isABigFlower(@RequestBody Flower flower) {
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.mockito.argumentmatchers.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baeldung.mockito.argumentmatchers.Message;
import com.baeldung.mockito.argumentmatchers.MessageDTO;
import com.baeldung.mockito.argumentmatchers.service.MessageService;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;
@Controller
@RequestMapping("/message")
public class MessageController {
@Autowired
private MessageService messageService;
@PostMapping
public Message createMessage(@RequestBody MessageDTO messageDTO) {
Message message = new Message();
message.setText(messageDTO.getText());
message.setFrom(messageDTO.getFrom());
message.setTo(messageDTO.getTo());
message.setDate(Date.from(Instant.now()));
message.setId(UUID.randomUUID());
return messageService.deliverMessage(message);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.domain.service;
package com.baeldung.mockito.argumentmatchers.service;
import org.springframework.stereotype.Service;

View File

@ -1,8 +1,9 @@
package com.baeldung.domain.service;
package com.baeldung.mockito.argumentmatchers.service;
import com.baeldung.domain.model.Message;
import org.springframework.stereotype.Service;
import com.baeldung.mockito.argumentmatchers.Message;
@Service
public class MessageService {

View File

@ -1,4 +1,4 @@
package com.baeldung.junit5.mockito;
package com.baeldung.mockito.junit5;
public class User {

View File

@ -0,0 +1,9 @@
package com.baeldung.mockito.junit5.repository;
import com.baeldung.mockito.junit5.User;
public interface MailClient {
void sendUserRegistrationMail(User user);
}

View File

@ -1,4 +1,4 @@
package com.baeldung.junit5.mockito.repository;
package com.baeldung.mockito.junit5.repository;
public interface SettingRepository {

View File

@ -1,6 +1,6 @@
package com.baeldung.junit5.mockito.repository;
package com.baeldung.mockito.junit5.repository;
import com.baeldung.junit5.mockito.User;
import com.baeldung.mockito.junit5.User;
public interface UserRepository {

View File

@ -1,9 +1,9 @@
package com.baeldung.junit5.mockito.service;
package com.baeldung.mockito.junit5.service;
import com.baeldung.junit5.mockito.User;
import com.baeldung.junit5.mockito.repository.MailClient;
import com.baeldung.junit5.mockito.repository.SettingRepository;
import com.baeldung.junit5.mockito.repository.UserRepository;
import com.baeldung.mockito.junit5.User;
import com.baeldung.mockito.junit5.repository.MailClient;
import com.baeldung.mockito.junit5.repository.SettingRepository;
import com.baeldung.mockito.junit5.repository.UserRepository;
public class DefaultUserService implements UserService {

View File

@ -1,4 +1,4 @@
package com.baeldung.junit5.mockito.service;
package com.baeldung.mockito.junit5.service;
public class Errors {

View File

@ -0,0 +1,9 @@
package com.baeldung.mockito.junit5.service;
import com.baeldung.mockito.junit5.User;
public interface UserService {
User register(User user);
}

View File

@ -6,17 +6,16 @@ import java.util.stream.IntStream;
public class StaticUtils {
private StaticUtils() {
}
private StaticUtils() {
}
public static List<Integer> range(int start, int end) {
return IntStream.range(start, end)
.boxed()
.collect(Collectors.toList());
}
public static String name() {
return "Baeldung";
}
public static List<Integer> range(int start, int end) {
return IntStream.range(start, end)
.boxed()
.collect(Collectors.toList());
}
public static String name() {
return "Baeldung";
}
}

View File

@ -1,56 +0,0 @@
package com.baeldung.app.rest;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
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 com.baeldung.app.api.MessageDTO;
import com.baeldung.domain.model.Message;
import com.baeldung.domain.service.MessageService;
import com.baeldung.domain.util.MessageMatcher;
@ExtendWith(MockitoExtension.class)
class MessageControllerUnitTest {
@InjectMocks
private MessageController messageController;
@Mock
private MessageService messageService;
@Test
void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
messageController.createMessage(messageDTO);
verify(messageService, times(1)).deliverMessage(any(Message.class));
}
@Test
void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
messageController.createMessage(messageDTO);
Message message = new Message();
message.setFrom("me");
message.setTo("you");
message.setText("Hello, you!");
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
}
}

View File

@ -2,9 +2,9 @@ package com.baeldung.mockito;
public final class FinalList extends MyList {
@Override
public int size() {
return 1;
}
@Override
public int size() {
return 1;
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.mockito;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class MockFinalsUnitTest {
@Test
void whenMockFinalMethodMockWorks() {
MyList myList = new MyList();
MyList mock = mock(MyList.class);
when(mock.finalMethod()).thenReturn(1);
assertThat(mock.finalMethod()).isNotEqualTo(myList.finalMethod());
}
@Test
public void whenMockFinalClassMockWorks() {
FinalList finalList = new FinalList();
FinalList mock = mock(FinalList.class);
when(mock.size()).thenReturn(2);
assertThat(mock.size()).isNotEqualTo(finalList.size());
}
}

View File

@ -1,127 +0,0 @@
package com.baeldung.mockito;
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.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class MockitoAnnotationUnitTest {
@Mock
private List<String> mockedList;
@Spy
private List<String> spiedList = new ArrayList<>();
// Use either @RunWith(MockitoJUnitRunner.class) or manually openMocks in the @Before method
/*
@Before
public void init() {
MockitoAnnotations.openMocks(this);
}
*/
// tests
@Test
void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = mock(List.class);
mockList.add("one");
verify(mockList).add("one");
assertEquals(0, mockList.size());
when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
@Test
void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one");
verify(mockedList).add("one");
assertEquals(0, mockedList.size());
when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size());
}
@Test
void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = spy(new ArrayList<String>());
spyList.add("one");
spyList.add("two");
verify(spyList).add("one");
verify(spyList).add("two");
assertEquals(2, spyList.size());
doReturn(100).when(spyList).size();
assertEquals(100, spyList.size());
}
@Test
void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one");
spiedList.add("two");
verify(spiedList).add("one");
verify(spiedList).add("two");
assertEquals(2, spiedList.size());
doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size());
}
@Test
void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = mock(List.class);
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one");
verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue());
}
@Captor
private
ArgumentCaptor<String> argCaptor;
@Test
void whenUseCaptorAnnotation_thenTheSame() {
mockedList.add("one");
verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue());
}
@Mock
private Map<String, String> wordMap;
@InjectMocks
private MyDictionary dic = new MyDictionary();
@Test
void whenUseInjectMocksAnnotation_thenCorrect() {
when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", dic.getMeaning("aWord"));
}
}

View File

@ -1,23 +0,0 @@
package com.baeldung.mockito;
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 java.util.List;
class MockitoAnnotationsUninitializedUnitTest {
@Mock
List<String> mockedList;
@Test
void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
assertThrows(NullPointerException.class, () -> {
when(mockedList.size()).thenReturn(1);
});
}
}

View File

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

View File

@ -1,67 +0,0 @@
package com.baeldung.mockito;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import org.junit.jupiter.api.Test;
import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
class MockitoMockUnitTest {
@Test
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).isFalse();
}
@Test
void whenUsingMockWithName_thenCorrect() {
MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
.isInstanceOf(TooFewActualInvocations.class)
.hasMessageContaining("myMock.add");
}
private static class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
}
}
@Test
void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added).isFalse();
}
@Test
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).isFalse();
}
}

View File

@ -1,130 +0,0 @@
package com.baeldung.mockito;
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.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import com.google.common.collect.Lists;
class MockitoVerifyExamplesUnitTest {
// tests
@Test
final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList).size();
}
@Test
final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, times(1)).size();
}
@Test
final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verifyNoInteractions(mockedList);
}
@Test
final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size();
}
@Test
final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.clear();
verify(mockedList).size();
assertThrows(NoInteractionsWanted.class, () -> {
verifyNoMoreInteractions(mockedList);
});
}
@Test
final void whenVerifyingOrderOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.add("a parameter");
mockedList.clear();
final InOrder inOrder = inOrder(mockedList);
inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear();
}
@Test
final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, never()).clear();
}
@Test
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
final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add("test");
}
@Test
final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add(anyString());
}
@Test
final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String>newArrayList("someElement"));
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
final List<String> capturedArgument = argumentCaptor.getValue();
assertThat(capturedArgument).contains("someElement");
}
}

View File

@ -1,108 +0,0 @@
package com.baeldung.mockito;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
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.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
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 org.junit.jupiter.api.Test;
class MockitoWhenThenExamplesUnitTest {
@Test
final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse();
}
@Test
final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final MyList listMock = mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse();
}
@Test
final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
assertThrows(IllegalStateException.class, () -> {
listMock.add(randomAlphabetic(6));
});
}
@Test
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
}
@Test
final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
final MyList listMock = mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
assertThrows(NullPointerException.class, () -> {
listMock.clear();
});
}
@Test
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
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();
assertThat(listMock).hasSize(1);
}
@Test
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1);
assertThat(element).isEqualTo("Always the same");
}
}

View File

@ -3,23 +3,23 @@ package com.baeldung.mockito;
import java.util.HashMap;
import java.util.Map;
class MyDictionary {
public class MyDictionary {
private Map<String, String> wordMap;
private Map<String, String> wordMap;
MyDictionary() {
wordMap = new HashMap<>();
}
public MyDictionary() {
wordMap = new HashMap<>();
}
MyDictionary(Map<String, String> wordMap) {
this.wordMap = wordMap;
}
public MyDictionary(Map<String, String> wordMap) {
this.wordMap = wordMap;
}
public void add(final String word, final String meaning) {
wordMap.put(word, meaning);
}
public void add(final String word, final String meaning) {
wordMap.put(word, meaning);
}
String getMeaning(final String word) {
return wordMap.get(word);
}
public String getMeaning(final String word) {
return wordMap.get(word);
}
}

View File

@ -4,22 +4,22 @@ import java.util.AbstractList;
public class MyList extends AbstractList<String> {
@Override
public String get(final int index) {
return null;
}
@Override
public String get(final int index) {
return null;
}
@Override
public int size() {
return 1;
}
@Override
public int size() {
return 1;
}
@Override
public void add(int index, String element) {
// no-op
}
@Override
public void add(int index, String element) {
// no-op
}
final public int finalMethod() {
return 0;
}
final public int finalMethod() {
return 0;
}
}

View File

@ -0,0 +1,130 @@
package com.baeldung.mockito.annotations;
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.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.mockito.MyDictionary;
@ExtendWith(MockitoExtension.class)
class MockitoAnnotationUnitTest {
@Mock
private List<String> mockedList;
@Spy
private List<String> spiedList = new ArrayList<>();
// Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method
/*
@BeforeEach
public void init() {
MockitoAnnotations.openMocks(this);
}
*/
// tests
@Test
void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = mock(ArrayList.class);
mockList.add("one");
verify(mockList).add("one");
assertEquals(0, mockList.size());
when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
@Test
void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one");
verify(mockedList).add("one");
assertEquals(0, mockedList.size());
when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size());
}
@Test
void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = spy(new ArrayList<String>());
spyList.add("one");
spyList.add("two");
verify(spyList).add("one");
verify(spyList).add("two");
assertEquals(2, spyList.size());
doReturn(100).when(spyList).size();
assertEquals(100, spyList.size());
}
@Test
void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one");
spiedList.add("two");
verify(spiedList).add("one");
verify(spiedList).add("two");
assertEquals(2, spiedList.size());
doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size());
}
@Test
void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = mock(List.class);
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one");
verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue());
}
@Captor
private ArgumentCaptor<String> argCaptor;
@Test
void whenUseCaptorAnnotation_thenTheSame() {
mockedList.add("one");
verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue());
}
@Mock
private Map<String, String> wordMap;
@InjectMocks
private MyDictionary dic = new MyDictionary();
@Test
void whenUseInjectMocksAnnotation_thenCorrect() {
when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", dic.getMeaning("aWord"));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.mockito;
package com.baeldung.mockito.annotations;
import org.junit.Rule;
import org.junit.Test;
@ -6,25 +6,23 @@ 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 MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
@Rule
public MockitoRule initRule = MockitoJUnit.rule();
@Rule
public MockitoRule initRule = MockitoJUnit.rule();
@Mock
private List<String> mockedList;
@Mock
private List<String> mockedList;
@Test
public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
when(mockedList.size()).thenReturn(41);
@Test
public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
when(mockedList.size()).thenReturn(41);
assertThat(mockedList).hasSize(41);
}
assertThat(mockedList).hasSize(41);
}
}

View File

@ -1,11 +1,12 @@
package com.baeldung.mockito;
package com.baeldung.mockito.annotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.openMocks;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -13,30 +14,29 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Map;
import com.baeldung.mockito.MyDictionary;
@ExtendWith(MockitoExtension.class)
class MockitoAnnotationsInjectIntoSpyUnitTest {
@BeforeEach
public void init() {
openMocks(this);
spyDic = spy(new MyDictionary(wordMap));
}
@BeforeEach
public void init() {
openMocks(this);
spyDic = spy(new MyDictionary(wordMap));
}
@Mock
private Map<String, String> wordMap;
@Mock
private Map<String, String> wordMap;
@InjectMocks
private MyDictionary dic = new MyDictionary();
@InjectMocks
private MyDictionary dic = new MyDictionary();
private MyDictionary spyDic;
private MyDictionary spyDic;
@Test
void whenUseInjectMocksAnnotation_thenCorrect() {
when(wordMap.get("aWord")).thenReturn("aMeaning");
@Test
void whenUseInjectMocksAnnotation_thenCorrect() {
when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
}
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
}
}

View File

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

View File

@ -18,84 +18,84 @@ import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class EmailServiceUnitTest {
@Mock
DeliveryPlatform platform;
@Mock
DeliveryPlatform platform;
@InjectMocks
EmailService emailService;
@InjectMocks
EmailService emailService;
@Captor
ArgumentCaptor<Email> emailCaptor;
@Captor
ArgumentCaptor<Email> emailCaptor;
@Captor
ArgumentCaptor<Credentials> credentialsCaptor;
@Captor
ArgumentCaptor<Credentials> credentialsCaptor;
@Test
void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor";
String body = "Hey, let'use ArgumentCaptor";
@Test
void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor";
String body = "Hey, let'use ArgumentCaptor";
emailService.send(to, subject, body, false);
emailService.send(to, subject, body, false);
verify(platform).deliver(emailCaptor.capture());
Email emailCaptorValue = emailCaptor.getValue();
assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY);
}
verify(platform).deliver(emailCaptor.capture());
Email emailCaptorValue = emailCaptor.getValue();
assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY);
}
@Test
void whenDoesSupportHtml_expectHTMLEmailFormat() {
String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor";
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
@Test
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);
emailService.send(to, subject, body, true);
verify(platform).deliver(emailCaptor.capture());
Email value = emailCaptor.getValue();
assertThat(value.getFormat()).isEqualTo(Format.HTML);
}
verify(platform).deliver(emailCaptor.capture());
Email value = emailCaptor.getValue();
assertThat(value.getFormat()).isEqualTo(Format.HTML);
}
@Test
void whenServiceRunning_expectUpResponse() {
when(platform.getServiceStatus()).thenReturn("OK");
@Test
void whenServiceRunning_expectUpResponse() {
when(platform.getServiceStatus()).thenReturn("OK");
ServiceStatus serviceStatus = emailService.checkServiceStatus();
ServiceStatus serviceStatus = emailService.checkServiceStatus();
assertThat(serviceStatus).isEqualTo(ServiceStatus.UP);
}
assertThat(serviceStatus).isEqualTo(ServiceStatus.UP);
}
@Test
void whenServiceNotRunning_expectDownResponse() {
when(platform.getServiceStatus()).thenReturn("Error");
@Test
void whenServiceNotRunning_expectDownResponse() {
when(platform.getServiceStatus()).thenReturn("Error");
ServiceStatus serviceStatus = emailService.checkServiceStatus();
ServiceStatus serviceStatus = emailService.checkServiceStatus();
assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN);
}
assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN);
}
@Test
void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
@Test
void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
assertTrue(emailService.authenticatedSuccessfully(credentials));
}
assertTrue(emailService.authenticatedSuccessfully(credentials));
}
@Test
void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
@Test
void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
assertTrue(emailService.authenticatedSuccessfully(credentials));
assertThat(credentialsCaptor.getValue()).isEqualTo(credentials);
}
assertTrue(emailService.authenticatedSuccessfully(credentials));
assertThat(credentialsCaptor.getValue()).isEqualTo(credentials);
}
@Test
void whenNotAuthenticated_expectFalse() {
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
@Test
void whenNotAuthenticated_expectFalse() {
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
assertFalse(emailService.authenticatedSuccessfully(credentials));
}
assertFalse(emailService.authenticatedSuccessfully(credentials));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.app.rest;
package com.baeldung.mockito.argumentmatchers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -18,8 +18,8 @@ import org.mockito.Mock;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.app.api.Flower;
import com.baeldung.domain.service.FlowerService;
import com.baeldung.mockito.argumentmatchers.controller.FlowerController;
import com.baeldung.mockito.argumentmatchers.service.FlowerService;
@ExtendWith(MockitoExtension.class)
class FlowerControllerUnitTest {
@ -39,7 +39,7 @@ class FlowerControllerUnitTest {
}
@Test
void givenAnyString_whenUsingArgumentMatcher_thenCorrect() {
void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() {
when(flowerService.analyze(anyString())).thenReturn("Flower");
String response = flowerController.isAFlower("violetta");
@ -47,19 +47,13 @@ class FlowerControllerUnitTest {
}
@Test
void whenIncorrectMatchers_thenThrowsError() {
assertThrows(InvalidUseOfMatchersException.class, () -> {
when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true);
});
Flower flower = new Flower("poppy", 15);
Boolean response = flowerController.isABigFlower(flower);
assertThat(response).isFalse();
void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() {
assertThrows(InvalidUseOfMatchersException.class,
() -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true));
}
@Test
void whenCorrectMatchers_thenCorrect() {
void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() {
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
Flower flower = new Flower("poppy", 15);
@ -69,26 +63,18 @@ class FlowerControllerUnitTest {
}
@Test
void whenUsingMatchersAsReturnValue_thenThrowsError() {
void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() {
flowerController.isAFlower("poppy");
String orMatcher = or(eq("poppy"), endsWith("y"));
assertThrows(InvalidUseOfMatchersException.class, () -> {
verify(flowerService).analyze(orMatcher);
});
assertThrows(InvalidUseOfMatchersException.class,
() -> verify(flowerService).analyze(orMatcher));
}
@Test
void whenUsingMatchersAsOngoingStubbing_thenCorrect1() {
void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() {
flowerController.isAFlower("poppy");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
}
@Test
void whenUsingMatchersAsOngoingStubbing_thenCorrect2() {
flowerController.isAFlower("lily");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.mockito.argumentmatchers;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
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 com.baeldung.mockito.argumentmatchers.controller.MessageController;
import com.baeldung.mockito.argumentmatchers.service.MessageService;
@ExtendWith(MockitoExtension.class)
class MessageControllerUnitTest {
@InjectMocks
private MessageController messageController;
@Mock
private MessageService messageService;
@Test
void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
messageController.createMessage(messageDTO);
verify(messageService, times(1)).deliverMessage(any(Message.class));
}
@Test
void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
messageController.createMessage(messageDTO);
Message message = new Message();
message.setFrom("me");
message.setTo("you");
message.setText("Hello, you!");
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.domain.util;
package com.baeldung.mockito.argumentmatchers;
import com.baeldung.domain.model.Message;
import org.mockito.ArgumentMatcher;
public class MessageMatcher implements ArgumentMatcher<Message> {

View File

@ -0,0 +1,105 @@
package com.baeldung.mockito.behaviour;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
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 org.junit.jupiter.api.Test;
import com.baeldung.mockito.MyList;
class MockitoWhenThenExamplesUnitTest {
@Test
final void whenSimpleReturnBehaviourConfigured_thenCorrect() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse();
}
@Test
final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() {
final MyList listMock = mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse();
}
@Test
final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6)));
}
@Test
final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
assertThrows(NullPointerException.class, () -> listMock.clear());
}
@Test
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
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 givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString()))
.thenReturn(false)
.thenThrow(IllegalStateException.class);
assertThatNoException().isThrownBy(() -> listMock.add(randomAlphabetic(6)));
}
@Test
final void whenSpyBehaviourConfigured_thenCorrect() {
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();
assertThat(listMock).hasSize(1);
}
@Test
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() {
final MyList listMock = mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1);
assertThat(element).isEqualTo("Always the same");
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.mockito.exceptions;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.jupiter.api.Test;
import org.mockito.Mockito;
import com.baeldung.mockito.MyDictionary;
class MockitoExceptionUnitTest {
@Test
void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
}
@Test
void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock).add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
}
@Test
void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
}
@Test
void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
}
@Test
void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
assertThrows(NullPointerException.class, () -> spy.getMeaning("word"));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.junit5.mockito;
package com.baeldung.mockito.junit5;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -18,12 +18,12 @@ 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;
import com.baeldung.mockito.junit5.repository.MailClient;
import com.baeldung.mockito.junit5.repository.SettingRepository;
import com.baeldung.mockito.junit5.repository.UserRepository;
import com.baeldung.mockito.junit5.service.DefaultUserService;
import com.baeldung.mockito.junit5.service.Errors;
import com.baeldung.mockito.junit5.service.UserService;
@ExtendWith(MockitoExtension.class)
class UserServiceUnitTest {
@ -43,11 +43,14 @@ class UserServiceUnitTest {
@BeforeEach
void init(@Mock SettingRepository settingRepository) {
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
lenient().when(settingRepository.getUserMinAge())
.thenReturn(10);
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
when(settingRepository.getUserNameMinLength()).thenReturn(4);
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class)))
.thenReturn(false);
this.settingRepository = settingRepository;
}
@ -77,6 +80,8 @@ class UserServiceUnitTest {
verify(mailClient).sendUserRegistrationMail(insertedUser);
}
//additional tests
@Test
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
// Given

View File

@ -1,39 +0,0 @@
package com.baeldung.mockito.mockedstatic;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mockStatic;
import java.util.Arrays;
class MockedStaticUnitTest {
@Test
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
try (MockedStatic<StaticUtils> utilities = 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 = 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);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.mockito.mockfinal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import com.baeldung.mockito.FinalList;
import com.baeldung.mockito.MyList;
class MockFinalsUnitTest {
@Test
void whenMockFinalMethod_thenMockWorks() {
MyList mock = mock(MyList.class);
when(mock.finalMethod()).thenReturn(1);
assertThat(mock.finalMethod()).isNotZero();
}
@Test
void whenMockFinalClass_thenMockWorks() {
FinalList mock = mock(FinalList.class);
when(mock.size()).thenReturn(2);
assertThat(mock.size()).isNotEqualTo(1);
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.mockito.mockmethods;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import org.junit.jupiter.api.Test;
import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.baeldung.mockito.MyList;
class MockitoMockMethodsUnitTest {
@Test
void whenUsingSimpleMock_thenCorrect() {
MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse();
verify(listMock).add(anyString());
}
@Test
void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() {
MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
.isInstanceOf(TooFewActualInvocations.class)
.hasMessageContaining("myMock.add");
}
private static class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
}
}
@Test
void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added).isFalse();
}
@Test
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).isFalse();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.mockito.mockstatic;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import com.baeldung.mockito.mockedstatic.StaticUtils;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mockStatic;
import java.util.Arrays;
class MockStaticUnitTest {
@Test
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
try (MockedStatic<StaticUtils> utilities = 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 = 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);
}
}

View File

@ -16,65 +16,66 @@ import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MockitoSpyUnitTest {
class MockitoSpyUnitTest {
@Test
void whenSpyingOnList_thenCorrect() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = spy(list);
@Test
void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = spy(list);
spyList.add("one");
spyList.add("two");
spyList.add("one");
spyList.add("two");
verify(spyList).add("one");
verify(spyList).add("two");
verify(spyList).add("one");
verify(spyList).add("two");
assertThat(spyList).hasSize(2);
}
assertThat(spyList).hasSize(2);
}
@Spy
private List<String> aSpyList = new ArrayList<String>();
@Spy
private List<String> aSpyList = new ArrayList<String>();
@Test
void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
aSpyList.add("one");
aSpyList.add("two");
@Test
void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() {
aSpyList.add("one");
aSpyList.add("two");
verify(aSpyList).add("one");
verify(aSpyList).add("two");
verify(aSpyList).add("one");
verify(aSpyList).add("two");
assertThat(aSpyList).hasSize(2);
}
assertThat(aSpyList).hasSize(2);
}
@Test
void whenStubASpy_thenStubbed() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = spy(list);
@Test
void givenASpy_whenStubbingTheBehaviour_thenCorrect() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = spy(list);
assertEquals(0, spyList.size());
assertEquals(0, spyList.size());
doReturn(100).when(spyList).size();
assertThat(spyList).hasSize(100);
}
doReturn(100).when(spyList).size();
assertThat(spyList).hasSize(100);
}
@Test
void whenCreateMock_thenCreated() {
final List<String> mockedList = mock(ArrayList.class);
@Test
void whenCreateMock_thenCreated() {
final List<String> mockedList = mock(ArrayList.class);
mockedList.add("one");
verify(mockedList).add("one");
mockedList.add("one");
verify(mockedList).add("one");
assertThat(mockedList).hasSize(0);
}
assertThat(mockedList).hasSize(0);
}
@Test
void whenCreateSpy_thenCreate() {
final List<String> spyList = spy(new ArrayList<>());
@Test
void whenCreateSpy_thenCreate() {
final List<String> spyList = spy(new ArrayList<>());
spyList.add("one");
verify(spyList).add("one");
spyList.add("one");
verify(spyList).add("one");
assertThat(spyList).hasSize(1);
}
assertThat(spyList).hasSize(1);
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.mockito.verify;
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.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import com.baeldung.mockito.MyList;
import com.google.common.collect.Lists;
class MockitoVerifyExamplesUnitTest {
@Test
final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList).size();
}
@Test
final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, times(1)).size();
}
@Test
final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verifyNoInteractions(mockedList);
}
@Test
final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size();
}
@Test
final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.clear();
verify(mockedList).size();
assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList));
}
@Test
final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.add("a parameter");
mockedList.clear();
final InOrder inOrder = inOrder(mockedList);
inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear();
}
@Test
final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, never()).clear();
}
@Test
final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_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
final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add("test");
}
@Test
final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add(anyString());
}
@Test
final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String> newArrayList("someElement"));
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
final List<String> capturedArgument = argumentCaptor.getValue();
assertThat(capturedArgument).contains("someElement");
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.mockito.voidmethods;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
@ -15,64 +14,75 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.mockito.MyList;
@ExtendWith(MockitoExtension.class)
class MockitoVoidMethodsUnitTest {
@Test
void whenAddCalledVerified() {
MyList myList = mock(MyList.class);
myList.add(0, "");
@Test
void whenAddCalled_thenVerified() {
MyList myList = mock(MyList.class);
doNothing().when(myList).add(isA(Integer.class), isA(String.class));
myList.add(0, "");
verify(myList, times(1)).add(0, "");
}
@Test
void whenAddCalled_thenVerified2() {
MyList myList = mock(MyList.class);
myList.add(0, "");
verify(myList, times(1)).add(0, "");
}
verify(myList, times(1)).add(0, "");
}
@Test
void givenNull_addThrows() {
MyList myList = mock(MyList.class);
assertThrows(Exception.class, () -> {
doThrow().when(myList).add(isA(Integer.class), isNull());
});
@Test
void givenNull_whenAddCalled_thenThrowsException() {
MyList myList = mock(MyList.class);
assertThrows(Exception.class, () -> {
doThrow().when(myList).add(isA(Integer.class), isNull());
});
myList.add(0, null);
}
myList.add(0, null);
}
@Test
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");
@Test
void givenArgumentCaptor_whenAddCalled_thenValueCaptured() {
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());
}
assertEquals("captured", valueCapture.getValue());
}
@Test
void whenAddCalledAnswered() {
MyList myList = mock(MyList.class);
doAnswer(invocation -> {
Object arg0 = invocation.getArgument(0);
Object arg1 = invocation.getArgument(1);
@Test
void givenDoAnswer_whenAddCalled_thenAnswered() {
MyList myList = mock(MyList.class);
//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");
}
doAnswer(invocation -> {
Object arg0 = invocation.getArgument(0);
Object arg1 = invocation.getArgument(1);
@Test
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");
}
assertEquals(3, arg0);
assertEquals("answer me", arg1);
return null;
}).when(myList).add(any(Integer.class), any(String.class));
myList.add(3, "answer me");
}
@Test
void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() {
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");
}
}