Merge pull request #13922 from dkapil/task/JAVA-13721

JAVA-13721 Format, Fix Package, Upgrade version of all the articles
This commit is contained in:
Loredana Crusoveanu 2023-05-18 11:31:42 +03:00 committed by GitHub
commit b688f123db
46 changed files with 367 additions and 363 deletions

View File

@ -794,6 +794,7 @@
<module>spring-reactive-modules</module>
<module>spring-swagger-codegen/custom-validations-opeanpi-codegen</module>
<module>testing-modules/testing-assertions</module>
<module>testing-modules/mockito-simple</module>
<module>persistence-modules/fauna</module>
<module>persistence-modules/spring-data-rest</module>
@ -1050,6 +1051,7 @@
<module>spring-reactive-modules</module>
<module>spring-swagger-codegen/custom-validations-opeanpi-codegen</module>
<module>testing-modules/testing-assertions</module>
<module>testing-modules/mockito-simple</module>
<module>persistence-modules/fauna</module>
<module>persistence-modules/spring-data-rest</module>

View File

@ -55,9 +55,8 @@
</build>
<properties>
<spring-framework.version>5.3.20</spring-framework.version>
<!-- testing -->
<mockito.version>4.8.0</mockito.version>
<spring-framework.version>6.0.8</spring-framework.version>
<mockito.version>5.3.1</mockito.version>
</properties>
</project>

View File

@ -1,13 +0,0 @@
package com.baeldung.domain.service;
import com.baeldung.domain.model.Message;
import org.springframework.stereotype.Service;
@Service
public class MessageService {
public Message deliverMessage (Message message) {
return message;
}
}

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,7 +1,5 @@
package com.baeldung.mockito.argumentcaptor;
public enum AuthenticationStatus {
AUTHENTICATED,
NOT_AUTHENTICATED,
ERROR
AUTHENTICATED, NOT_AUTHENTICATED, ERROR
}

View File

@ -10,5 +10,16 @@ public class Credentials {
this.password = password;
this.key = key;
}
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public String getKey() {
return key;
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.mockito.argumentcaptor;
public enum Format {
TEXT_ONLY,
HTML
TEXT_ONLY, HTML
}

View File

@ -1,7 +1,5 @@
package com.baeldung.mockito.argumentcaptor;
public enum ServiceStatus {
UP,
DOWN,
AUTHENTICATED
UP, DOWN, AUTHENTICATED
}

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung.domain.model;
package com.baeldung.mockito.argumentmatchers;
import java.util.Date;
import java.util.UUID;

View File

@ -1,6 +1,7 @@
package com.baeldung.app.api;
package com.baeldung.mockito.argumentmatchers;
public class MessageDTO {
private String from;
private String to;
private String text;

View File

@ -1,13 +1,14 @@
package com.baeldung.app.rest;
package com.baeldung.mockito.argumentmatchers.controller;
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;
import com.baeldung.mockito.argumentmatchers.Flower;
import com.baeldung.mockito.argumentmatchers.service.FlowerService;
@Controller
@RequestMapping("/flowers")
public class FlowerController {
@ -16,12 +17,12 @@ public class FlowerController {
private FlowerService flowerService;
@PostMapping("/isAFlower")
public String isAFlower (@RequestBody String flower) {
public String isAFlower(@RequestBody String flower) {
return flowerService.analyze(flower);
}
@PostMapping("/isABigFlower")
public Boolean isABigFlower (@RequestBody Flower flower) {
public Boolean isABigFlower(@RequestBody Flower flower) {
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
}
}

View File

@ -1,14 +1,15 @@
package com.baeldung.app.rest;
package com.baeldung.mockito.argumentmatchers.controller;
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 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;
@ -21,7 +22,7 @@ public class MessageController {
private MessageService messageService;
@PostMapping
public Message createMessage (@RequestBody MessageDTO messageDTO) {
public Message createMessage(@RequestBody MessageDTO messageDTO) {
Message message = new Message();
message.setText(messageDTO.getText());
message.setFrom(messageDTO.getFrom());

View File

@ -1,4 +1,4 @@
package com.baeldung.domain.service;
package com.baeldung.mockito.argumentmatchers.service;
import org.springframework.stereotype.Service;
@ -11,15 +11,15 @@ public class FlowerService {
private List<String> flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana");
public String analyze(String name) {
if(flowers.contains(name)) {
if (flowers.contains(name)) {
return "flower";
}
return null;
}
public boolean isABigFlower(String name, int petals) {
if(flowers.contains(name)) {
if(petals > 10) {
if (flowers.contains(name)) {
if (petals > 10) {
return true;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.mockito.argumentmatchers.service;
import org.springframework.stereotype.Service;
import com.baeldung.mockito.argumentmatchers.Message;
@Service
public class MessageService {
public Message deliverMessage(Message message) {
return message;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.junit5.mockito;
package com.baeldung.mockito.junit5;
public class User {
@ -17,18 +17,23 @@ public class User {
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

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,10 +1,11 @@
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 {
User insert(User user);
boolean isUsernameAlreadyExists(String userName);
}

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 {
@ -26,19 +26,20 @@ public class DefaultUserService implements UserService {
}
private void validate(User user) {
if(user.getName() == null) {
if (user.getName() == null) {
throw new RuntimeException(Errors.USER_NAME_REQUIRED);
}
if(user.getName().length() < settingRepository.getUserNameMinLength()) {
if (user.getName()
.length() < settingRepository.getUserNameMinLength()) {
throw new RuntimeException(Errors.USER_NAME_SHORT);
}
if(user.getAge() < settingRepository.getUserMinAge()) {
if (user.getAge() < settingRepository.getUserMinAge()) {
throw new RuntimeException(Errors.USER_AGE_YOUNG);
}
if(userRepository.isUsernameAlreadyExists(user.getName())) {
if (userRepository.isUsernameAlreadyExists(user.getName())) {
throw new RuntimeException(Errors.USER_NAME_DUPLICATE);
}
}

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

@ -18,5 +18,4 @@ public class StaticUtils {
public static String name() {
return "Baeldung";
}
}

View File

@ -1,94 +0,0 @@
package com.baeldung.app.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
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;
@ExtendWith(MockitoExtension.class)
class FlowerControllerUnitTest {
@InjectMocks
private FlowerController flowerController;
@Mock
private FlowerService flowerService;
@Test
void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
doReturn("Flower").when(flowerService).analyze("poppy");
String response = flowerController.isAFlower("poppy");
assertThat(response).isEqualTo("Flower");
}
@Test
void givenAnyString_whenUsingArgumentMatcher_thenCorrect() {
when(flowerService.analyze(anyString())).thenReturn("Flower");
String response = flowerController.isAFlower("violetta");
assertThat(response).isEqualTo("Flower");
}
@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();
}
@Test
void whenCorrectMatchers_thenCorrect() {
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
Flower flower = new Flower("poppy", 15);
Boolean response = flowerController.isABigFlower(flower);
assertThat(response).isTrue();
}
@Test
void whenUsingMatchersAsReturnValue_thenThrowsError() {
flowerController.isAFlower("poppy");
String orMatcher = or(eq("poppy"), endsWith("y"));
assertThrows(InvalidUseOfMatchersException.class, () -> {
verify(flowerService).analyze(orMatcher);
});
}
@Test
void whenUsingMatchersAsOngoingStubbing_thenCorrect1() {
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

@ -1,22 +0,0 @@
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;
}
}

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

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

View File

@ -1,4 +1,4 @@
package com.baeldung.mockito;
package com.baeldung.mockito.annotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
@ -20,6 +20,8 @@ import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.mockito.MyDictionary;
@ExtendWith(MockitoExtension.class)
class MockitoAnnotationUnitTest {
@ -29,11 +31,11 @@ class MockitoAnnotationUnitTest {
@Spy
private List<String> spiedList = new ArrayList<>();
// Use either @RunWith(MockitoJUnitRunner.class) or manually openMocks in the @Before method
// Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method
/*
@Before
@BeforeEach
public void init() {
MockitoAnnotations.openMocks(this);
MockitoAnnotations.openMocks(this);
}
*/
@ -41,7 +43,8 @@ class MockitoAnnotationUnitTest {
@Test
void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = mock(List.class);
final List<String> mockList = mock(ArrayList.class);
mockList.add("one");
verify(mockList).add("one");
assertEquals(0, mockList.size());
@ -63,6 +66,7 @@ class MockitoAnnotationUnitTest {
@Test
void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = spy(new ArrayList<String>());
spyList.add("one");
spyList.add("two");
@ -93,6 +97,7 @@ class MockitoAnnotationUnitTest {
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());
@ -100,8 +105,7 @@ class MockitoAnnotationUnitTest {
}
@Captor
private
ArgumentCaptor<String> argCaptor;
private ArgumentCaptor<String> argCaptor;
@Test
void whenUseCaptorAnnotation_thenTheSame() {
@ -123,5 +127,4 @@ class MockitoAnnotationUnitTest {
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,13 +6,11 @@ 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

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,8 +14,7 @@ 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 {

View File

@ -1,14 +1,13 @@
package com.baeldung.mockito;
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;
import java.util.List;
class MockitoAnnotationsUninitializedUnitTest {
@Mock

View File

@ -0,0 +1,80 @@
package com.baeldung.mockito.argumentmatchers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.mockito.argumentmatchers.controller.FlowerController;
import com.baeldung.mockito.argumentmatchers.service.FlowerService;
@ExtendWith(MockitoExtension.class)
class FlowerControllerUnitTest {
@InjectMocks
private FlowerController flowerController;
@Mock
private FlowerService flowerService;
@Test
void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
doReturn("Flower").when(flowerService).analyze("poppy");
String response = flowerController.isAFlower("poppy");
assertThat(response).isEqualTo("Flower");
}
@Test
void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() {
when(flowerService.analyze(anyString())).thenReturn("Flower");
String response = flowerController.isAFlower("violetta");
assertThat(response).isEqualTo("Flower");
}
@Test
void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() {
assertThrows(InvalidUseOfMatchersException.class,
() -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true));
}
@Test
void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() {
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
Flower flower = new Flower("poppy", 15);
Boolean response = flowerController.isABigFlower(flower);
assertThat(response).isTrue();
}
@Test
void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() {
flowerController.isAFlower("poppy");
String orMatcher = or(eq("poppy"), endsWith("y"));
assertThrows(InvalidUseOfMatchersException.class,
() -> verify(flowerService).analyze(orMatcher));
}
@Test
void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() {
flowerController.isAFlower("poppy");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.app.rest;
package com.baeldung.mockito.argumentmatchers;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
@ -11,10 +11,8 @@ 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;
import com.baeldung.mockito.argumentmatchers.controller.MessageController;
import com.baeldung.mockito.argumentmatchers.service.MessageService;
@ExtendWith(MockitoExtension.class)
class MessageControllerUnitTest {

View File

@ -0,0 +1,20 @@
package com.baeldung.mockito.argumentmatchers;
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;
}
}

View File

@ -1,7 +1,8 @@
package com.baeldung.mockito;
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;
@ -14,11 +15,12 @@ import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import com.baeldung.mockito.MyList;
class MockitoWhenThenExamplesUnitTest {
@Test
final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final void whenSimpleReturnBehaviourConfigured_thenCorrect() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
@ -27,7 +29,7 @@ class MockitoWhenThenExamplesUnitTest {
}
@Test
final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() {
final MyList listMock = mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
@ -40,53 +42,48 @@ class MockitoWhenThenExamplesUnitTest {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
assertThrows(IllegalStateException.class, () -> {
listMock.add(randomAlphabetic(6));
});
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 void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
assertThrows(NullPointerException.class, () -> {
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);
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 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();
});
assertThrows(NullPointerException.class, () -> spy.size());
}
@Test
@ -98,7 +95,7 @@ class MockitoWhenThenExamplesUnitTest {
}
@Test
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() {
final MyList listMock = mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());

View File

@ -1,4 +1,4 @@
package com.baeldung.mockito;
package com.baeldung.mockito.exceptions;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
@ -6,66 +6,53 @@ 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)
import com.baeldung.mockito.MyDictionary;
class MockitoExceptionUnitTest {
@Test
void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
assertThrows(NullPointerException.class, () -> {
dictMock.getMeaning("word");
});
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
}
@Test
void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> {
dictMock.add("word", "meaning");
});
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
}
@Test
void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
assertThrows(NullPointerException.class, () -> {
dictMock.getMeaning("word");
});
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
}
@Test
void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
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");
});
doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
}
// =====
@Test
void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
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");
});
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,4 +1,4 @@
package com.baeldung.mockito;
package com.baeldung.mockito.mockfinal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@ -8,28 +8,27 @@ import static org.mockito.Mockito.withSettings;
import org.junit.jupiter.api.Test;
import org.mockito.MockMakers;
import com.baeldung.mockito.FinalList;
import com.baeldung.mockito.MyList;
class MockFinalsUnitTest {
@Test
void whenMockFinalMethodMockWorks() {
MyList myList = new MyList();
void whenMockFinalMethod_thenMockWorks() {
MyList mock = mock(MyList.class);
when(mock.finalMethod()).thenReturn(1);
assertThat(mock.finalMethod()).isNotEqualTo(myList.finalMethod());
assertThat(mock.finalMethod()).isNotZero();
}
@Test
public void whenMockFinalClassMockWorks() {
FinalList finalList = new FinalList();
void whenMockFinalClass_thenMockWorks() {
FinalList mock = mock(FinalList.class);
when(mock.size()).thenReturn(2);
assertThat(mock.size()).isNotEqualTo(finalList.size());
assertThat(mock.size()).isNotEqualTo(1);
}
@Test

View File

@ -1,4 +1,4 @@
package com.baeldung.mockito;
package com.baeldung.mockito.mockmethods;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
@ -16,30 +16,35 @@ import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
class MockitoMockUnitTest {
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));
verify(listMock).add(anyString());
assertThat(added).isFalse();
verify(listMock).add(anyString());
}
@Test
void whenUsingMockWithName_thenCorrect() {
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");
.isInstanceOf(TooFewActualInvocations.class)
.hasMessageContaining("myMock.add");
}
private static class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
@ -59,6 +64,7 @@ class MockitoMockUnitTest {
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());

View File

@ -1,14 +1,16 @@
package com.baeldung.mockito.mockedstatic;
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 MockedStaticUnitTest {
class MockStaticUnitTest {
@Test
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {

View File

@ -18,8 +18,8 @@ class MockitoMisusingMockOrSpyUnitTest {
List<String> list = new ArrayList<String>();
assertThatThrownBy(() -> doReturn(100).when(list).size())
.isInstanceOf(NotAMockException.class)
.hasMessageContaining("Argument passed to when() is not a mock!");
.isInstanceOf(NotAMockException.class)
.hasMessageContaining("Argument passed to when() is not a mock!");
}
@Test

View File

@ -16,10 +16,10 @@ import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MockitoSpyUnitTest {
class MockitoSpyUnitTest {
@Test
void whenSpyingOnList_thenCorrect() {
void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = spy(list);
@ -36,7 +36,7 @@ public class MockitoSpyUnitTest {
private List<String> aSpyList = new ArrayList<String>();
@Test
void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() {
aSpyList.add("one");
aSpyList.add("two");
@ -47,13 +47,14 @@ public class MockitoSpyUnitTest {
}
@Test
void whenStubASpy_thenStubbed() {
void givenASpy_whenStubbingTheBehaviour_thenCorrect() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = spy(list);
assertEquals(0, spyList.size());
doReturn(100).when(spyList).size();
assertThat(spyList).hasSize(100);
}

View File

@ -1,4 +1,4 @@
package com.baeldung.mockito;
package com.baeldung.mockito.verify;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -20,34 +20,33 @@ 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 {
// tests
@Test
final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList).size();
}
@Test
final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, times(1)).size();
}
@Test
final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verifyNoInteractions(mockedList);
}
@Test
final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size();
}
@ -59,14 +58,12 @@ class MockitoVerifyExamplesUnitTest {
mockedList.clear();
verify(mockedList).size();
assertThrows(NoInteractionsWanted.class, () -> {
verifyNoMoreInteractions(mockedList);
});
assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList));
}
@Test
final void whenVerifyingOrderOfInteractions_thenCorrect() {
final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.add("a parameter");
@ -79,7 +76,7 @@ class MockitoVerifyExamplesUnitTest {
}
@Test
final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
@ -87,7 +84,7 @@ class MockitoVerifyExamplesUnitTest {
}
@Test
final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.clear();
mockedList.clear();
@ -100,7 +97,7 @@ class MockitoVerifyExamplesUnitTest {
// with arguments
@Test
final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
@ -108,7 +105,7 @@ class MockitoVerifyExamplesUnitTest {
}
@Test
final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
@ -116,9 +113,9 @@ class MockitoVerifyExamplesUnitTest {
}
@Test
final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String>newArrayList("someElement"));
mockedList.addAll(Lists.<String> newArrayList("someElement"));
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
@ -126,5 +123,4 @@ class MockitoVerifyExamplesUnitTest {
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,17 +14,23 @@ 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() {
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, "");
@ -33,8 +38,9 @@ class MockitoVoidMethodsUnitTest {
}
@Test
void givenNull_addThrows() {
void givenNull_whenAddCalled_thenThrowsException() {
MyList myList = mock(MyList.class);
assertThrows(Exception.class, () -> {
doThrow().when(myList).add(isA(Integer.class), isNull());
});
@ -43,34 +49,40 @@ class MockitoVoidMethodsUnitTest {
}
@Test
void whenAddCalledValueCaptured() {
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());
}
@Test
void whenAddCalledAnswered() {
void givenDoAnswer_whenAddCalled_thenAnswered() {
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));
}).when(myList)
.add(any(Integer.class), any(String.class));
myList.add(3, "answer me");
}
@Test
void whenAddCalledRealMethodCalled() {
void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() {
MyList myList = mock(MyList.class);
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
doCallRealMethod().when(myList)
.add(any(Integer.class), any(String.class));
myList.add(1, "real");
verify(myList, times(1)).add(1, "real");

View File

@ -31,7 +31,7 @@
<module>junit5-migration</module>
<module>load-testing-comparison</module>
<module>mockito</module>
<module>mockito-simple</module>
<!-- <module>mockito-simple</module> --> <!-- Uncomment when testing-modules is moved to JDK9+ -->
<module>mocks</module>
<module>mocks-2</module>
<module>mockserver</module>