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:
commit
b688f123db
2
pom.xml
2
pom.xml
|
@ -794,6 +794,7 @@
|
||||||
<module>spring-reactive-modules</module>
|
<module>spring-reactive-modules</module>
|
||||||
<module>spring-swagger-codegen/custom-validations-opeanpi-codegen</module>
|
<module>spring-swagger-codegen/custom-validations-opeanpi-codegen</module>
|
||||||
<module>testing-modules/testing-assertions</module>
|
<module>testing-modules/testing-assertions</module>
|
||||||
|
<module>testing-modules/mockito-simple</module>
|
||||||
<module>persistence-modules/fauna</module>
|
<module>persistence-modules/fauna</module>
|
||||||
<module>persistence-modules/spring-data-rest</module>
|
<module>persistence-modules/spring-data-rest</module>
|
||||||
|
|
||||||
|
@ -1050,6 +1051,7 @@
|
||||||
<module>spring-reactive-modules</module>
|
<module>spring-reactive-modules</module>
|
||||||
<module>spring-swagger-codegen/custom-validations-opeanpi-codegen</module>
|
<module>spring-swagger-codegen/custom-validations-opeanpi-codegen</module>
|
||||||
<module>testing-modules/testing-assertions</module>
|
<module>testing-modules/testing-assertions</module>
|
||||||
|
<module>testing-modules/mockito-simple</module>
|
||||||
<module>persistence-modules/fauna</module>
|
<module>persistence-modules/fauna</module>
|
||||||
<module>persistence-modules/spring-data-rest</module>
|
<module>persistence-modules/spring-data-rest</module>
|
||||||
|
|
||||||
|
|
|
@ -55,9 +55,8 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-framework.version>5.3.20</spring-framework.version>
|
<spring-framework.version>6.0.8</spring-framework.version>
|
||||||
<!-- testing -->
|
<mockito.version>5.3.1</mockito.version>
|
||||||
<mockito.version>4.8.0</mockito.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,9 +0,0 @@
|
||||||
package com.baeldung.junit5.mockito.repository;
|
|
||||||
|
|
||||||
import com.baeldung.junit5.mockito.User;
|
|
||||||
|
|
||||||
public interface MailClient {
|
|
||||||
|
|
||||||
void sendUserRegistrationMail(User user);
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,9 +0,0 @@
|
||||||
package com.baeldung.junit5.mockito.service;
|
|
||||||
|
|
||||||
import com.baeldung.junit5.mockito.User;
|
|
||||||
|
|
||||||
public interface UserService {
|
|
||||||
|
|
||||||
User register(User user);
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,7 +1,5 @@
|
||||||
package com.baeldung.mockito.argumentcaptor;
|
package com.baeldung.mockito.argumentcaptor;
|
||||||
|
|
||||||
public enum AuthenticationStatus {
|
public enum AuthenticationStatus {
|
||||||
AUTHENTICATED,
|
AUTHENTICATED, NOT_AUTHENTICATED, ERROR
|
||||||
NOT_AUTHENTICATED,
|
|
||||||
ERROR
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,5 +10,16 @@ public class Credentials {
|
||||||
this.password = password;
|
this.password = password;
|
||||||
this.key = key;
|
this.key = key;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getKey() {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.mockito.argumentcaptor;
|
package com.baeldung.mockito.argumentcaptor;
|
||||||
|
|
||||||
public enum Format {
|
public enum Format {
|
||||||
TEXT_ONLY,
|
TEXT_ONLY, HTML
|
||||||
HTML
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,5 @@
|
||||||
package com.baeldung.mockito.argumentcaptor;
|
package com.baeldung.mockito.argumentcaptor;
|
||||||
|
|
||||||
public enum ServiceStatus {
|
public enum ServiceStatus {
|
||||||
UP,
|
UP, DOWN, AUTHENTICATED
|
||||||
DOWN,
|
|
||||||
AUTHENTICATED
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.app.api;
|
package com.baeldung.mockito.argumentmatchers;
|
||||||
|
|
||||||
public class Flower {
|
public class Flower {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.domain.model;
|
package com.baeldung.mockito.argumentmatchers;
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
|
@ -1,6 +1,7 @@
|
||||||
package com.baeldung.app.api;
|
package com.baeldung.mockito.argumentmatchers;
|
||||||
|
|
||||||
public class MessageDTO {
|
public class MessageDTO {
|
||||||
|
|
||||||
private String from;
|
private String from;
|
||||||
private String to;
|
private String to;
|
||||||
private String text;
|
private String text;
|
|
@ -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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.argumentmatchers.Flower;
|
||||||
|
import com.baeldung.mockito.argumentmatchers.service.FlowerService;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
@RequestMapping("/flowers")
|
@RequestMapping("/flowers")
|
||||||
public class FlowerController {
|
public class FlowerController {
|
||||||
|
@ -16,12 +17,12 @@ public class FlowerController {
|
||||||
private FlowerService flowerService;
|
private FlowerService flowerService;
|
||||||
|
|
||||||
@PostMapping("/isAFlower")
|
@PostMapping("/isAFlower")
|
||||||
public String isAFlower (@RequestBody String flower) {
|
public String isAFlower(@RequestBody String flower) {
|
||||||
return flowerService.analyze(flower);
|
return flowerService.analyze(flower);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/isABigFlower")
|
@PostMapping("/isABigFlower")
|
||||||
public Boolean isABigFlower (@RequestBody Flower flower) {
|
public Boolean isABigFlower(@RequestBody Flower flower) {
|
||||||
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
|
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
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.time.Instant;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
@ -21,7 +22,7 @@ public class MessageController {
|
||||||
private MessageService messageService;
|
private MessageService messageService;
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public Message createMessage (@RequestBody MessageDTO messageDTO) {
|
public Message createMessage(@RequestBody MessageDTO messageDTO) {
|
||||||
Message message = new Message();
|
Message message = new Message();
|
||||||
message.setText(messageDTO.getText());
|
message.setText(messageDTO.getText());
|
||||||
message.setFrom(messageDTO.getFrom());
|
message.setFrom(messageDTO.getFrom());
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.domain.service;
|
package com.baeldung.mockito.argumentmatchers.service;
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@ -11,15 +11,15 @@ public class FlowerService {
|
||||||
private List<String> flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana");
|
private List<String> flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana");
|
||||||
|
|
||||||
public String analyze(String name) {
|
public String analyze(String name) {
|
||||||
if(flowers.contains(name)) {
|
if (flowers.contains(name)) {
|
||||||
return "flower";
|
return "flower";
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isABigFlower(String name, int petals) {
|
public boolean isABigFlower(String name, int petals) {
|
||||||
if(flowers.contains(name)) {
|
if (flowers.contains(name)) {
|
||||||
if(petals > 10) {
|
if (petals > 10) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,34 +1,39 @@
|
||||||
package com.baeldung.junit5.mockito;
|
package com.baeldung.mockito.junit5;
|
||||||
|
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
private Integer id;
|
private Integer id;
|
||||||
private String name;
|
private String name;
|
||||||
private int age;
|
private int age;
|
||||||
|
|
||||||
public User() {
|
public User() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public User(String name, int age) {
|
public User(String name, int age) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getId() {
|
public Integer getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(Integer id) {
|
public void setId(Integer id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getAge() {
|
public int getAge() {
|
||||||
return age;
|
return age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAge(int age) {
|
public void setAge(int age) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.mockito.junit5.repository;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.junit5.User;
|
||||||
|
|
||||||
|
public interface MailClient {
|
||||||
|
|
||||||
|
void sendUserRegistrationMail(User user);
|
||||||
|
|
||||||
|
}
|
|
@ -1,7 +1,7 @@
|
||||||
package com.baeldung.junit5.mockito.repository;
|
package com.baeldung.mockito.junit5.repository;
|
||||||
|
|
||||||
public interface SettingRepository {
|
public interface SettingRepository {
|
||||||
|
|
||||||
int getUserMinAge();
|
int getUserMinAge();
|
||||||
|
|
||||||
int getUserNameMinLength();
|
int getUserNameMinLength();
|
|
@ -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 {
|
public interface UserRepository {
|
||||||
|
|
||||||
User insert(User user);
|
User insert(User user);
|
||||||
|
|
||||||
boolean isUsernameAlreadyExists(String userName);
|
boolean isUsernameAlreadyExists(String userName);
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,16 +1,16 @@
|
||||||
package com.baeldung.junit5.mockito.service;
|
package com.baeldung.mockito.junit5.service;
|
||||||
|
|
||||||
import com.baeldung.junit5.mockito.User;
|
import com.baeldung.mockito.junit5.User;
|
||||||
import com.baeldung.junit5.mockito.repository.MailClient;
|
import com.baeldung.mockito.junit5.repository.MailClient;
|
||||||
import com.baeldung.junit5.mockito.repository.SettingRepository;
|
import com.baeldung.mockito.junit5.repository.SettingRepository;
|
||||||
import com.baeldung.junit5.mockito.repository.UserRepository;
|
import com.baeldung.mockito.junit5.repository.UserRepository;
|
||||||
|
|
||||||
public class DefaultUserService implements UserService {
|
public class DefaultUserService implements UserService {
|
||||||
|
|
||||||
private UserRepository userRepository;
|
private UserRepository userRepository;
|
||||||
private SettingRepository settingRepository;
|
private SettingRepository settingRepository;
|
||||||
private MailClient mailClient;
|
private MailClient mailClient;
|
||||||
|
|
||||||
public DefaultUserService(UserRepository userRepository, SettingRepository settingRepository, MailClient mailClient) {
|
public DefaultUserService(UserRepository userRepository, SettingRepository settingRepository, MailClient mailClient) {
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
this.settingRepository = settingRepository;
|
this.settingRepository = settingRepository;
|
||||||
|
@ -26,19 +26,20 @@ public class DefaultUserService implements UserService {
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validate(User user) {
|
private void validate(User user) {
|
||||||
if(user.getName() == null) {
|
if (user.getName() == null) {
|
||||||
throw new RuntimeException(Errors.USER_NAME_REQUIRED);
|
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);
|
throw new RuntimeException(Errors.USER_NAME_SHORT);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(user.getAge() < settingRepository.getUserMinAge()) {
|
if (user.getAge() < settingRepository.getUserMinAge()) {
|
||||||
throw new RuntimeException(Errors.USER_AGE_YOUNG);
|
throw new RuntimeException(Errors.USER_AGE_YOUNG);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(userRepository.isUsernameAlreadyExists(user.getName())) {
|
if (userRepository.isUsernameAlreadyExists(user.getName())) {
|
||||||
throw new RuntimeException(Errors.USER_NAME_DUPLICATE);
|
throw new RuntimeException(Errors.USER_NAME_DUPLICATE);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.junit5.mockito.service;
|
package com.baeldung.mockito.junit5.service;
|
||||||
|
|
||||||
public class Errors {
|
public class Errors {
|
||||||
|
|
||||||
|
@ -6,5 +6,5 @@ public class Errors {
|
||||||
public static final String USER_NAME_SHORT = "user.name.short";
|
public static final String USER_NAME_SHORT = "user.name.short";
|
||||||
public static final String USER_AGE_YOUNG = "user.age.young";
|
public static final String USER_AGE_YOUNG = "user.age.young";
|
||||||
public static final String USER_NAME_DUPLICATE = "user.name.duplicate";
|
public static final String USER_NAME_DUPLICATE = "user.name.duplicate";
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.mockito.junit5.service;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.junit5.User;
|
||||||
|
|
||||||
|
public interface UserService {
|
||||||
|
|
||||||
|
User register(User user);
|
||||||
|
|
||||||
|
}
|
|
@ -18,5 +18,4 @@ public class StaticUtils {
|
||||||
public static String name() {
|
public static String name() {
|
||||||
return "Baeldung";
|
return "Baeldung";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -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")));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -2,9 +2,9 @@ package com.baeldung.mockito;
|
||||||
|
|
||||||
public final class FinalList extends MyList {
|
public final class FinalList extends MyList {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int size() {
|
public int size() {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,15 +3,15 @@ package com.baeldung.mockito;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
class MyDictionary {
|
public class MyDictionary {
|
||||||
|
|
||||||
private Map<String, String> wordMap;
|
private Map<String, String> wordMap;
|
||||||
|
|
||||||
MyDictionary() {
|
public MyDictionary() {
|
||||||
wordMap = new HashMap<>();
|
wordMap = new HashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
MyDictionary(Map<String, String> wordMap) {
|
public MyDictionary(Map<String, String> wordMap) {
|
||||||
this.wordMap = wordMap;
|
this.wordMap = wordMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,7 +19,7 @@ class MyDictionary {
|
||||||
wordMap.put(word, meaning);
|
wordMap.put(word, meaning);
|
||||||
}
|
}
|
||||||
|
|
||||||
String getMeaning(final String word) {
|
public String getMeaning(final String word) {
|
||||||
return wordMap.get(word);
|
return wordMap.get(word);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.annotations;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.mockito.Mockito.doReturn;
|
import static org.mockito.Mockito.doReturn;
|
||||||
|
@ -20,6 +20,8 @@ import org.mockito.Mock;
|
||||||
import org.mockito.Spy;
|
import org.mockito.Spy;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.MyDictionary;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MockitoAnnotationUnitTest {
|
class MockitoAnnotationUnitTest {
|
||||||
|
|
||||||
|
@ -29,19 +31,20 @@ class MockitoAnnotationUnitTest {
|
||||||
@Spy
|
@Spy
|
||||||
private List<String> spiedList = new ArrayList<>();
|
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() {
|
public void init() {
|
||||||
MockitoAnnotations.openMocks(this);
|
MockitoAnnotations.openMocks(this);
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenNotUseMockAnnotation_thenCorrect() {
|
void whenNotUseMockAnnotation_thenCorrect() {
|
||||||
final List<String> mockList = mock(List.class);
|
final List<String> mockList = mock(ArrayList.class);
|
||||||
|
|
||||||
mockList.add("one");
|
mockList.add("one");
|
||||||
verify(mockList).add("one");
|
verify(mockList).add("one");
|
||||||
assertEquals(0, mockList.size());
|
assertEquals(0, mockList.size());
|
||||||
|
@ -63,6 +66,7 @@ class MockitoAnnotationUnitTest {
|
||||||
@Test
|
@Test
|
||||||
void whenNotUseSpyAnnotation_thenCorrect() {
|
void whenNotUseSpyAnnotation_thenCorrect() {
|
||||||
final List<String> spyList = spy(new ArrayList<String>());
|
final List<String> spyList = spy(new ArrayList<String>());
|
||||||
|
|
||||||
spyList.add("one");
|
spyList.add("one");
|
||||||
spyList.add("two");
|
spyList.add("two");
|
||||||
|
|
||||||
|
@ -88,11 +92,12 @@ class MockitoAnnotationUnitTest {
|
||||||
doReturn(100).when(spiedList).size();
|
doReturn(100).when(spiedList).size();
|
||||||
assertEquals(100, spiedList.size());
|
assertEquals(100, spiedList.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenNotUseCaptorAnnotation_thenCorrect() {
|
void whenNotUseCaptorAnnotation_thenCorrect() {
|
||||||
final List<String> mockList = mock(List.class);
|
final List<String> mockList = mock(List.class);
|
||||||
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
|
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
|
||||||
|
|
||||||
mockList.add("one");
|
mockList.add("one");
|
||||||
verify(mockList).add(arg.capture());
|
verify(mockList).add(arg.capture());
|
||||||
|
|
||||||
|
@ -100,8 +105,7 @@ class MockitoAnnotationUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Captor
|
@Captor
|
||||||
private
|
private ArgumentCaptor<String> argCaptor;
|
||||||
ArgumentCaptor<String> argCaptor;
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUseCaptorAnnotation_thenTheSame() {
|
void whenUseCaptorAnnotation_thenTheSame() {
|
||||||
|
@ -123,5 +127,4 @@ class MockitoAnnotationUnitTest {
|
||||||
|
|
||||||
assertEquals("aMeaning", dic.getMeaning("aWord"));
|
assertEquals("aMeaning", dic.getMeaning("aWord"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.annotations;
|
||||||
|
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
@ -6,13 +6,11 @@ import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnit;
|
import org.mockito.junit.MockitoJUnit;
|
||||||
import org.mockito.junit.MockitoRule;
|
import org.mockito.junit.MockitoRule;
|
||||||
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
|
||||||
public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
|
public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
|
||||||
|
|
||||||
@Rule
|
@Rule
|
|
@ -1,11 +1,12 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.annotations;
|
||||||
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static org.mockito.MockitoAnnotations.openMocks;
|
import static org.mockito.MockitoAnnotations.openMocks;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
@ -13,8 +14,7 @@ import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.util.Map;
|
import com.baeldung.mockito.MyDictionary;
|
||||||
|
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MockitoAnnotationsInjectIntoSpyUnitTest {
|
class MockitoAnnotationsInjectIntoSpyUnitTest {
|
|
@ -1,14 +1,13 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.annotations;
|
||||||
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
class MockitoAnnotationsUninitializedUnitTest {
|
class MockitoAnnotationsUninitializedUnitTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
|
@ -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")));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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.any;
|
||||||
import static org.mockito.ArgumentMatchers.argThat;
|
import static org.mockito.ArgumentMatchers.argThat;
|
||||||
|
@ -11,10 +11,8 @@ import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import com.baeldung.app.api.MessageDTO;
|
import com.baeldung.mockito.argumentmatchers.controller.MessageController;
|
||||||
import com.baeldung.domain.model.Message;
|
import com.baeldung.mockito.argumentmatchers.service.MessageService;
|
||||||
import com.baeldung.domain.service.MessageService;
|
|
||||||
import com.baeldung.domain.util.MessageMatcher;
|
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MessageControllerUnitTest {
|
class MessageControllerUnitTest {
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,8 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.behaviour;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.mockito.ArgumentMatchers.anyInt;
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
@ -14,11 +15,12 @@ import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
class MockitoWhenThenExamplesUnitTest {
|
class MockitoWhenThenExamplesUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
|
final void whenSimpleReturnBehaviourConfigured_thenCorrect() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenReturn(false);
|
when(listMock.add(anyString())).thenReturn(false);
|
||||||
|
|
||||||
|
@ -27,7 +29,7 @@ class MockitoWhenThenExamplesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
|
final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
doReturn(false).when(listMock).add(anyString());
|
doReturn(false).when(listMock).add(anyString());
|
||||||
|
|
||||||
|
@ -40,55 +42,50 @@ class MockitoWhenThenExamplesUnitTest {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
|
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
|
||||||
|
|
||||||
assertThrows(IllegalStateException.class, () -> {
|
assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6)));
|
||||||
listMock.add(randomAlphabetic(6));
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
|
final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() {
|
||||||
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);
|
final MyList listMock = mock(MyList.class);
|
||||||
doThrow(NullPointerException.class).when(listMock).clear();
|
doThrow(NullPointerException.class).when(listMock).clear();
|
||||||
|
|
||||||
assertThrows(NullPointerException.class, () -> {
|
assertThrows(NullPointerException.class, () -> listMock.clear());
|
||||||
listMock.clear();
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
|
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
|
when(listMock.add(anyString()))
|
||||||
|
.thenReturn(false)
|
||||||
|
.thenThrow(IllegalStateException.class);
|
||||||
|
|
||||||
assertThrows(IllegalStateException.class, () -> {
|
assertThrows(IllegalStateException.class, () -> {
|
||||||
listMock.add(randomAlphabetic(6));
|
listMock.add(randomAlphabetic(6));
|
||||||
listMock.add(randomAlphabetic(6));
|
listMock.add(randomAlphabetic(6));
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@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 instance = new MyList();
|
||||||
final MyList spy = spy(instance);
|
final MyList spy = spy(instance);
|
||||||
|
|
||||||
doThrow(NullPointerException.class).when(spy).size();
|
doThrow(NullPointerException.class).when(spy).size();
|
||||||
assertThrows(NullPointerException.class, () -> {
|
|
||||||
spy.size();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class, () -> spy.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
|
final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
|
@ -96,9 +93,9 @@ class MockitoWhenThenExamplesUnitTest {
|
||||||
|
|
||||||
assertThat(listMock).hasSize(1);
|
assertThat(listMock).hasSize(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
|
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
|
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.exceptions;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
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.mock;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
import com.baeldung.mockito.MyDictionary;
|
||||||
|
|
||||||
class MockitoExceptionUnitTest {
|
class MockitoExceptionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
|
void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
||||||
assertThrows(NullPointerException.class, () -> {
|
|
||||||
dictMock.getMeaning("word");
|
|
||||||
});
|
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
|
void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
doThrow(IllegalStateException.class).when(dictMock)
|
doThrow(IllegalStateException.class).when(dictMock)
|
||||||
.add(anyString(), anyString());
|
.add(anyString(), anyString());
|
||||||
assertThrows(IllegalStateException.class, () -> {
|
|
||||||
dictMock.add("word", "meaning");
|
|
||||||
});
|
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
|
void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
|
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
|
||||||
assertThrows(NullPointerException.class, () -> {
|
|
||||||
dictMock.getMeaning("word");
|
|
||||||
});
|
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
|
void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
|
doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString());
|
||||||
.add(anyString(), anyString());
|
|
||||||
assertThrows(IllegalStateException.class, () -> {
|
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
|
||||||
dictMock.add("word", "meaning");
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// =====
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
|
void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
|
||||||
MyDictionary dict = new MyDictionary();
|
MyDictionary dict = new MyDictionary();
|
||||||
MyDictionary spy = Mockito.spy(dict);
|
MyDictionary spy = Mockito.spy(dict);
|
||||||
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
||||||
assertThrows(NullPointerException.class, () -> {
|
|
||||||
spy.getMeaning("word");
|
assertThrows(NullPointerException.class, () -> spy.getMeaning("word"));
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
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.junit.jupiter.MockitoExtension;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
import com.baeldung.junit5.mockito.repository.MailClient;
|
import com.baeldung.mockito.junit5.repository.MailClient;
|
||||||
import com.baeldung.junit5.mockito.repository.SettingRepository;
|
import com.baeldung.mockito.junit5.repository.SettingRepository;
|
||||||
import com.baeldung.junit5.mockito.repository.UserRepository;
|
import com.baeldung.mockito.junit5.repository.UserRepository;
|
||||||
import com.baeldung.junit5.mockito.service.DefaultUserService;
|
import com.baeldung.mockito.junit5.service.DefaultUserService;
|
||||||
import com.baeldung.junit5.mockito.service.Errors;
|
import com.baeldung.mockito.junit5.service.Errors;
|
||||||
import com.baeldung.junit5.mockito.service.UserService;
|
import com.baeldung.mockito.junit5.service.UserService;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class UserServiceUnitTest {
|
class UserServiceUnitTest {
|
||||||
|
@ -43,11 +43,14 @@ class UserServiceUnitTest {
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void init(@Mock SettingRepository settingRepository) {
|
void init(@Mock SettingRepository settingRepository) {
|
||||||
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
||||||
lenient().when(settingRepository.getUserMinAge())
|
|
||||||
.thenReturn(10);
|
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
|
||||||
|
|
||||||
when(settingRepository.getUserNameMinLength()).thenReturn(4);
|
when(settingRepository.getUserNameMinLength()).thenReturn(4);
|
||||||
|
|
||||||
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class)))
|
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class)))
|
||||||
.thenReturn(false);
|
.thenReturn(false);
|
||||||
|
|
||||||
this.settingRepository = settingRepository;
|
this.settingRepository = settingRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -77,6 +80,8 @@ class UserServiceUnitTest {
|
||||||
verify(mailClient).sendUserRegistrationMail(insertedUser);
|
verify(mailClient).sendUserRegistrationMail(insertedUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// additional tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
|
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
|
||||||
// Given
|
// Given
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.mockfinal;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -8,28 +8,27 @@ import static org.mockito.Mockito.withSettings;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.MockMakers;
|
import org.mockito.MockMakers;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.FinalList;
|
||||||
|
import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
class MockFinalsUnitTest {
|
class MockFinalsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenMockFinalMethodMockWorks() {
|
void whenMockFinalMethod_thenMockWorks() {
|
||||||
|
|
||||||
MyList myList = new MyList();
|
|
||||||
|
|
||||||
MyList mock = mock(MyList.class);
|
MyList mock = mock(MyList.class);
|
||||||
when(mock.finalMethod()).thenReturn(1);
|
when(mock.finalMethod()).thenReturn(1);
|
||||||
|
|
||||||
assertThat(mock.finalMethod()).isNotEqualTo(myList.finalMethod());
|
assertThat(mock.finalMethod()).isNotZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMockFinalClassMockWorks() {
|
void whenMockFinalClass_thenMockWorks() {
|
||||||
|
|
||||||
FinalList finalList = new FinalList();
|
|
||||||
|
|
||||||
FinalList mock = mock(FinalList.class);
|
FinalList mock = mock(FinalList.class);
|
||||||
when(mock.size()).thenReturn(2);
|
when(mock.size()).thenReturn(2);
|
||||||
|
|
||||||
assertThat(mock.size()).isNotEqualTo(finalList.size());
|
assertThat(mock.size()).isNotEqualTo(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.mockmethods;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
@ -16,36 +16,41 @@ import org.mockito.exceptions.verification.TooFewActualInvocations;
|
||||||
import org.mockito.invocation.InvocationOnMock;
|
import org.mockito.invocation.InvocationOnMock;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
class MockitoMockUnitTest {
|
import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
|
class MockitoMockMethodsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingSimpleMock_thenCorrect() {
|
void whenUsingSimpleMock_thenCorrect() {
|
||||||
MyList listMock = mock(MyList.class);
|
MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenReturn(false);
|
when(listMock.add(anyString())).thenReturn(false);
|
||||||
|
|
||||||
boolean added = listMock.add(randomAlphabetic(6));
|
boolean added = listMock.add(randomAlphabetic(6));
|
||||||
|
|
||||||
verify(listMock).add(anyString());
|
|
||||||
assertThat(added).isFalse();
|
assertThat(added).isFalse();
|
||||||
|
verify(listMock).add(anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingMockWithName_thenCorrect() {
|
void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() {
|
||||||
MyList listMock = mock(MyList.class, "myMock");
|
MyList listMock = mock(MyList.class, "myMock");
|
||||||
|
|
||||||
when(listMock.add(anyString())).thenReturn(false);
|
when(listMock.add(anyString())).thenReturn(false);
|
||||||
listMock.add(randomAlphabetic(6));
|
listMock.add(randomAlphabetic(6));
|
||||||
|
|
||||||
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
|
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
|
||||||
.isInstanceOf(TooFewActualInvocations.class)
|
.isInstanceOf(TooFewActualInvocations.class)
|
||||||
.hasMessageContaining("myMock.add");
|
.hasMessageContaining("myMock.add");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class CustomAnswer implements Answer<Boolean> {
|
private static class CustomAnswer implements Answer<Boolean> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingMockWithAnswer_thenCorrect() {
|
void whenUsingMockWithAnswer_thenCorrect() {
|
||||||
MyList listMock = mock(MyList.class, new CustomAnswer());
|
MyList listMock = mock(MyList.class, new CustomAnswer());
|
||||||
|
@ -59,6 +64,7 @@ class MockitoMockUnitTest {
|
||||||
void whenUsingMockWithSettings_thenCorrect() {
|
void whenUsingMockWithSettings_thenCorrect() {
|
||||||
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
||||||
MyList listMock = mock(MyList.class, customSettings);
|
MyList listMock = mock(MyList.class, customSettings);
|
||||||
|
|
||||||
boolean added = listMock.add(randomAlphabetic(6));
|
boolean added = listMock.add(randomAlphabetic(6));
|
||||||
|
|
||||||
verify(listMock).add(anyString());
|
verify(listMock).add(anyString());
|
|
@ -1,14 +1,16 @@
|
||||||
package com.baeldung.mockito.mockedstatic;
|
package com.baeldung.mockito.mockstatic;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.MockedStatic;
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.mockedstatic.StaticUtils;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.*;
|
import static org.assertj.core.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.mockStatic;
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
class MockedStaticUnitTest {
|
class MockStaticUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
|
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
|
|
@ -18,14 +18,14 @@ class MockitoMisusingMockOrSpyUnitTest {
|
||||||
List<String> list = new ArrayList<String>();
|
List<String> list = new ArrayList<String>();
|
||||||
|
|
||||||
assertThatThrownBy(() -> doReturn(100).when(list).size())
|
assertThatThrownBy(() -> doReturn(100).when(list).size())
|
||||||
.isInstanceOf(NotAMockException.class)
|
.isInstanceOf(NotAMockException.class)
|
||||||
.hasMessageContaining("Argument passed to when() is not a mock!");
|
.hasMessageContaining("Argument passed to when() is not a mock!");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenASpy_whenDoReturn_thenNoError() {
|
void givenASpy_whenDoReturn_thenNoError() {
|
||||||
final List<String> spyList = spy(new ArrayList<>());
|
final List<String> spyList = spy(new ArrayList<>());
|
||||||
|
|
||||||
assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());
|
assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,10 +16,10 @@ import org.mockito.Spy;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class MockitoSpyUnitTest {
|
class MockitoSpyUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenSpyingOnList_thenCorrect() {
|
void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() {
|
||||||
final List<String> list = new ArrayList<String>();
|
final List<String> list = new ArrayList<String>();
|
||||||
final List<String> spyList = spy(list);
|
final List<String> spyList = spy(list);
|
||||||
|
|
||||||
|
@ -36,7 +36,7 @@ public class MockitoSpyUnitTest {
|
||||||
private List<String> aSpyList = new ArrayList<String>();
|
private List<String> aSpyList = new ArrayList<String>();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
|
void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() {
|
||||||
aSpyList.add("one");
|
aSpyList.add("one");
|
||||||
aSpyList.add("two");
|
aSpyList.add("two");
|
||||||
|
|
||||||
|
@ -47,13 +47,14 @@ public class MockitoSpyUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenStubASpy_thenStubbed() {
|
void givenASpy_whenStubbingTheBehaviour_thenCorrect() {
|
||||||
final List<String> list = new ArrayList<String>();
|
final List<String> list = new ArrayList<String>();
|
||||||
final List<String> spyList = spy(list);
|
final List<String> spyList = spy(list);
|
||||||
|
|
||||||
assertEquals(0, spyList.size());
|
assertEquals(0, spyList.size());
|
||||||
|
|
||||||
doReturn(100).when(spyList).size();
|
doReturn(100).when(spyList).size();
|
||||||
|
|
||||||
assertThat(spyList).hasSize(100);
|
assertThat(spyList).hasSize(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.mockito;
|
package com.baeldung.mockito.verify;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
@ -20,34 +20,33 @@ import org.mockito.ArgumentCaptor;
|
||||||
import org.mockito.InOrder;
|
import org.mockito.InOrder;
|
||||||
import org.mockito.exceptions.verification.NoInteractionsWanted;
|
import org.mockito.exceptions.verification.NoInteractionsWanted;
|
||||||
|
|
||||||
|
import com.baeldung.mockito.MyList;
|
||||||
import com.google.common.collect.Lists;
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
class MockitoVerifyExamplesUnitTest {
|
class MockitoVerifyExamplesUnitTest {
|
||||||
|
|
||||||
// tests
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
|
final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
verify(mockedList).size();
|
verify(mockedList).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
|
final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
verify(mockedList, times(1)).size();
|
verify(mockedList, times(1)).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
|
final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
verifyNoInteractions(mockedList);
|
verifyNoInteractions(mockedList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
|
final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
verify(mockedList, times(0)).size();
|
verify(mockedList, times(0)).size();
|
||||||
}
|
}
|
||||||
|
@ -59,14 +58,12 @@ class MockitoVerifyExamplesUnitTest {
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
|
|
||||||
verify(mockedList).size();
|
verify(mockedList).size();
|
||||||
assertThrows(NoInteractionsWanted.class, () -> {
|
|
||||||
verifyNoMoreInteractions(mockedList);
|
|
||||||
});
|
|
||||||
|
|
||||||
|
assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenVerifyingOrderOfInteractions_thenCorrect() {
|
final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
mockedList.add("a parameter");
|
mockedList.add("a parameter");
|
||||||
|
@ -79,7 +76,7 @@ class MockitoVerifyExamplesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
|
final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
|
|
||||||
|
@ -87,7 +84,7 @@ class MockitoVerifyExamplesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
|
final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
|
@ -100,7 +97,7 @@ class MockitoVerifyExamplesUnitTest {
|
||||||
// with arguments
|
// with arguments
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
|
final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.add("test");
|
mockedList.add("test");
|
||||||
|
|
||||||
|
@ -108,7 +105,7 @@ class MockitoVerifyExamplesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
|
final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.add("test");
|
mockedList.add("test");
|
||||||
|
|
||||||
|
@ -116,15 +113,14 @@ class MockitoVerifyExamplesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.addAll(Lists.<String>newArrayList("someElement"));
|
mockedList.addAll(Lists.<String> newArrayList("someElement"));
|
||||||
|
|
||||||
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
||||||
verify(mockedList).addAll(argumentCaptor.capture());
|
verify(mockedList).addAll(argumentCaptor.capture());
|
||||||
|
|
||||||
final List<String> capturedArgument = argumentCaptor.getValue();
|
final List<String> capturedArgument = argumentCaptor.getValue();
|
||||||
assertThat(capturedArgument).contains("someElement");
|
assertThat(capturedArgument).contains("someElement");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.mockito.voidmethods;
|
package com.baeldung.mockito.voidmethods;
|
||||||
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
@ -15,17 +14,23 @@ import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
|
||||||
|
|
||||||
import com.baeldung.mockito.MyList;
|
import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
|
||||||
class MockitoVoidMethodsUnitTest {
|
class MockitoVoidMethodsUnitTest {
|
||||||
|
|
||||||
@Test
|
@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 myList = mock(MyList.class);
|
||||||
myList.add(0, "");
|
myList.add(0, "");
|
||||||
|
|
||||||
|
@ -33,8 +38,9 @@ class MockitoVoidMethodsUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenNull_addThrows() {
|
void givenNull_whenAddCalled_thenThrowsException() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
assertThrows(Exception.class, () -> {
|
assertThrows(Exception.class, () -> {
|
||||||
doThrow().when(myList).add(isA(Integer.class), isNull());
|
doThrow().when(myList).add(isA(Integer.class), isNull());
|
||||||
});
|
});
|
||||||
|
@ -43,36 +49,42 @@ class MockitoVoidMethodsUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenAddCalledValueCaptured() {
|
void givenArgumentCaptor_whenAddCalled_thenValueCaptured() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
|
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
|
||||||
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
|
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
|
||||||
|
|
||||||
myList.add(0, "captured");
|
myList.add(0, "captured");
|
||||||
|
|
||||||
assertEquals("captured", valueCapture.getValue());
|
assertEquals("captured", valueCapture.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenAddCalledAnswered() {
|
void givenDoAnswer_whenAddCalled_thenAnswered() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
doAnswer(invocation -> {
|
doAnswer(invocation -> {
|
||||||
Object arg0 = invocation.getArgument(0);
|
Object arg0 = invocation.getArgument(0);
|
||||||
Object arg1 = invocation.getArgument(1);
|
Object arg1 = invocation.getArgument(1);
|
||||||
|
|
||||||
//do something with the arguments here
|
|
||||||
assertEquals(3, arg0);
|
assertEquals(3, arg0);
|
||||||
assertEquals("answer me", arg1);
|
assertEquals("answer me", arg1);
|
||||||
return null;
|
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");
|
myList.add(3, "answer me");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenAddCalledRealMethodCalled() {
|
void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
|
|
||||||
|
doCallRealMethod().when(myList)
|
||||||
|
.add(any(Integer.class), any(String.class));
|
||||||
myList.add(1, "real");
|
myList.add(1, "real");
|
||||||
|
|
||||||
verify(myList, times(1)).add(1, "real");
|
verify(myList, times(1)).add(1, "real");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,7 +31,7 @@
|
||||||
<module>junit5-migration</module>
|
<module>junit5-migration</module>
|
||||||
<module>load-testing-comparison</module>
|
<module>load-testing-comparison</module>
|
||||||
<module>mockito</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</module>
|
||||||
<module>mocks-2</module>
|
<module>mocks-2</module>
|
||||||
<module>mockserver</module>
|
<module>mockserver</module>
|
||||||
|
|
Loading…
Reference in New Issue