JAVA-12032 Move Mockito ebook articles code to common module - mockito-simple- Delete mockito-3 since it had only 1 article which was moved to mockito-simple
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
### Mockito Articles that are also part of the e-book
|
||||
|
||||
This module contains articles about Mockito that are also part of an Ebook.
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks](https://www.baeldung.com/mockito-annotations)
|
||||
- [Mockito When/Then Cookbook](https://www.baeldung.com/mockito-behavior)
|
||||
- [Mockito’s Mock Methods](https://www.baeldung.com/mockito-mock-methods)
|
||||
- [Mockito Verify Cookbook](https://www.baeldung.com/mockito-verify)
|
||||
- [Mockito ArgumentMatchers](https://www.baeldung.com/mockito-argument-matchers)
|
||||
- [Mockito – Using Spies](https://www.baeldung.com/mockito-spy)
|
||||
- [Using Mockito ArgumentCaptor](https://www.baeldung.com/mockito-argumentcaptor)
|
||||
- [Mocking Void Methods with Mockito](https://www.baeldung.com/mockito-void-methods)
|
||||
- [Mocking Static Methods With Mockito](https://www.baeldung.com/mockito-mock-static-methods)
|
||||
- [Mock Final Classes and Methods with Mockito](https://www.baeldung.com/mockito-final)
|
||||
- [Mocking Exception Throwing using Mockito](https://www.baeldung.com/mockito-exceptions)
|
||||
- [Mockito and JUnit 5 – Using ExtendWith](https://www.baeldung.com/mockito-junit-5-extension)
|
||||
|
||||
|
||||
### NOTE:
|
||||
|
||||
Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article.
|
||||
@@ -0,0 +1,88 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>mockito-simple</artifactId>
|
||||
<name>mockito-simple</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${spring-data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>javax.persistence</artifactId>
|
||||
<version>${javax.persistence.version}</version>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>mockito-simple</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
|
||||
<spring-framework.version>5.0.8.RELEASE</spring-framework.version>
|
||||
<spring-data.version>2.0.9.RELEASE</spring-data.version>
|
||||
<!-- testing -->
|
||||
<powermock.version>2.0.2</powermock.version>
|
||||
<javax.persistence.version>2.1.1</javax.persistence.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.app.api;
|
||||
|
||||
public class Flower {
|
||||
|
||||
private String name;
|
||||
private Integer petals;
|
||||
|
||||
public Flower(String name, Integer petals) {
|
||||
this.name = name;
|
||||
this.petals = petals;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getPetals() {
|
||||
return petals;
|
||||
}
|
||||
|
||||
public void setPetals(Integer petals) {
|
||||
this.petals = petals;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.app.api;
|
||||
|
||||
public class MessageApi {
|
||||
private String from;
|
||||
private String to;
|
||||
private String text;
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.app.rest;
|
||||
|
||||
import com.baeldung.app.api.Flower;
|
||||
import com.baeldung.domain.service.FlowerService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/flowers")
|
||||
public class FlowerController {
|
||||
|
||||
@Autowired
|
||||
private FlowerService flowerService;
|
||||
|
||||
@PostMapping("/isAFlower")
|
||||
public String isAFlower (@RequestBody String flower) {
|
||||
return flowerService.analize(flower);
|
||||
}
|
||||
|
||||
@PostMapping("/isABigFlower")
|
||||
public Boolean isABigFlower (@RequestBody Flower flower) {
|
||||
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.app.rest;
|
||||
|
||||
import com.baeldung.app.api.MessageApi;
|
||||
import com.baeldung.domain.model.Message;
|
||||
import com.baeldung.domain.service.MessageService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/message")
|
||||
public class MessageController {
|
||||
|
||||
@Autowired
|
||||
private MessageService messageService;
|
||||
|
||||
@PostMapping
|
||||
public Message createMessage (@RequestBody MessageApi messageDTO) {
|
||||
Message message = new Message();
|
||||
message.setText(messageDTO.getText());
|
||||
message.setFrom(messageDTO.getFrom());
|
||||
message.setTo(messageDTO.getTo());
|
||||
message.setDate(Date.from(Instant.now()));
|
||||
message.setId(UUID.randomUUID());
|
||||
|
||||
return messageService.deliverMessage(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.domain.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Message {
|
||||
|
||||
private String from;
|
||||
private String to;
|
||||
private String text;
|
||||
private Date date;
|
||||
private UUID id;
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.domain.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class FlowerService {
|
||||
|
||||
private List<String> flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana");
|
||||
|
||||
public String analize(String name) {
|
||||
if(flowers.contains(name)) {
|
||||
return "flower";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isABigFlower(String name, int petals) {
|
||||
if(flowers.contains(name)) {
|
||||
if(petals > 10) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.junit5.mockito;
|
||||
|
||||
public class User {
|
||||
|
||||
private Integer id;
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.junit5.mockito.repository;
|
||||
|
||||
import com.baeldung.junit5.mockito.User;
|
||||
|
||||
public interface MailClient {
|
||||
|
||||
void sendUserRegistrationMail(User user);
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.junit5.mockito.repository;
|
||||
|
||||
public interface SettingRepository {
|
||||
|
||||
int getUserMinAge();
|
||||
|
||||
int getUserNameMinLength();
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.junit5.mockito.repository;
|
||||
|
||||
import com.baeldung.junit5.mockito.User;
|
||||
|
||||
public interface UserRepository {
|
||||
|
||||
User insert(User user);
|
||||
boolean isUsernameAlreadyExists(String userName);
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.junit5.mockito.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;
|
||||
|
||||
public class DefaultUserService implements UserService {
|
||||
|
||||
private UserRepository userRepository;
|
||||
private SettingRepository settingRepository;
|
||||
private MailClient mailClient;
|
||||
|
||||
public DefaultUserService(UserRepository userRepository, SettingRepository settingRepository, MailClient mailClient) {
|
||||
this.userRepository = userRepository;
|
||||
this.settingRepository = settingRepository;
|
||||
this.mailClient = mailClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public User register(User user) {
|
||||
validate(user);
|
||||
User insertedUser = userRepository.insert(user);
|
||||
mailClient.sendUserRegistrationMail(insertedUser);
|
||||
return insertedUser;
|
||||
}
|
||||
|
||||
private void validate(User user) {
|
||||
if(user.getName() == null) {
|
||||
throw new RuntimeException(Errors.USER_NAME_REQUIRED);
|
||||
}
|
||||
|
||||
if(user.getName().length() < settingRepository.getUserNameMinLength()) {
|
||||
throw new RuntimeException(Errors.USER_NAME_SHORT);
|
||||
}
|
||||
|
||||
if(user.getAge() < settingRepository.getUserMinAge()) {
|
||||
throw new RuntimeException(Errors.USER_AGE_YOUNG);
|
||||
}
|
||||
|
||||
if(userRepository.isUsernameAlreadyExists(user.getName())) {
|
||||
throw new RuntimeException(Errors.USER_NAME_DUPLICATE);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.junit5.mockito.service;
|
||||
|
||||
public class Errors {
|
||||
|
||||
public static final String USER_NAME_REQUIRED = "user.name.required";
|
||||
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_NAME_DUPLICATE = "user.name.duplicate";
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.junit5.mockito.service;
|
||||
|
||||
import com.baeldung.junit5.mockito.User;
|
||||
|
||||
public interface UserService {
|
||||
|
||||
User register(User user);
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public enum AuthenticationStatus {
|
||||
AUTHENTICATED,
|
||||
NOT_AUTHENTICATED,
|
||||
ERROR
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public class Credentials {
|
||||
private final String name;
|
||||
private final String password;
|
||||
private final String key;
|
||||
|
||||
public Credentials(String name, String password, String key) {
|
||||
this.name = name;
|
||||
this.password = password;
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public interface DeliveryPlatform {
|
||||
|
||||
void deliver(Email email);
|
||||
|
||||
String getServiceStatus();
|
||||
|
||||
AuthenticationStatus authenticate(Credentials credentials);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public class Email {
|
||||
|
||||
private String address;
|
||||
private String subject;
|
||||
private String body;
|
||||
private Format format;
|
||||
|
||||
public Email(String address, String subject, String body) {
|
||||
this.address = address;
|
||||
this.subject = subject;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Format getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public void setFormat(Format format) {
|
||||
this.format = format;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public class EmailService {
|
||||
|
||||
private DeliveryPlatform platform;
|
||||
|
||||
public EmailService(DeliveryPlatform platform) {
|
||||
this.platform = platform;
|
||||
}
|
||||
|
||||
public void send(String to, String subject, String body, boolean html) {
|
||||
Format format = Format.TEXT_ONLY;
|
||||
if (html) {
|
||||
format = Format.HTML;
|
||||
}
|
||||
Email email = new Email(to, subject, body);
|
||||
email.setFormat(format);
|
||||
platform.deliver(email);
|
||||
}
|
||||
|
||||
public ServiceStatus checkServiceStatus() {
|
||||
if (platform.getServiceStatus().equals("OK")) {
|
||||
return ServiceStatus.UP;
|
||||
} else {
|
||||
return ServiceStatus.DOWN;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean authenticatedSuccessfully(Credentials credentials) {
|
||||
if (platform.authenticate(credentials).equals(AuthenticationStatus.AUTHENTICATED)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public enum Format {
|
||||
TEXT_ONLY,
|
||||
HTML
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public enum ServiceStatus {
|
||||
UP,
|
||||
DOWN,
|
||||
AUTHENTICATED
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.mockito.mockedstatic;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class StaticUtils {
|
||||
|
||||
private StaticUtils() {
|
||||
}
|
||||
|
||||
public static List<Integer> range(int start, int end) {
|
||||
return IntStream.range(start, end)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static String name() {
|
||||
return "Baeldung";
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.app.rest;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import com.baeldung.app.api.Flower;
|
||||
import com.baeldung.domain.service.FlowerService;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class FlowerControllerUnitTest {
|
||||
|
||||
@Mock
|
||||
private FlowerService flowerService;
|
||||
|
||||
@InjectMocks
|
||||
private FlowerController flowerController;
|
||||
|
||||
@Test
|
||||
public void isAFlower_withMockito_OK() {
|
||||
when(flowerService.analize(eq("violetta"))).thenReturn("Flower");
|
||||
|
||||
String response = flowerController.isAFlower("violetta");
|
||||
|
||||
Assert.assertEquals("Flower", response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isABigFlower_withMockito_OK() {
|
||||
when(flowerService.isABigFlower(eq("violetta"), anyInt())).thenReturn(true);
|
||||
|
||||
Flower flower = new Flower("violetta", 15);
|
||||
|
||||
Boolean response = flowerController.isABigFlower(flower);
|
||||
|
||||
Assert.assertTrue(response);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.app.rest;
|
||||
|
||||
import static org.mockito.Mockito.times;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import com.baeldung.app.api.MessageApi;
|
||||
import com.baeldung.domain.model.Message;
|
||||
import com.baeldung.domain.service.MessageService;
|
||||
import com.baeldung.domain.util.MessageMatcher;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MessageControllerUnitTest {
|
||||
|
||||
@Mock
|
||||
private MessageService messageService;
|
||||
|
||||
@InjectMocks
|
||||
private MessageController messageController;
|
||||
|
||||
@Test
|
||||
public void createMessage_NewMessage_OK() {
|
||||
MessageApi messageApi = new MessageApi();
|
||||
messageApi.setFrom("me");
|
||||
messageApi.setTo("you");
|
||||
messageApi.setText("Hello, you!");
|
||||
|
||||
messageController.createMessage(messageApi);
|
||||
|
||||
Message message = new Message();
|
||||
message.setFrom("me");
|
||||
message.setTo("you");
|
||||
message.setText("Hello, you!");
|
||||
|
||||
Mockito.verify(messageService, times(1)).deliverMessage(ArgumentMatchers.argThat(new MessageMatcher(message)));
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.domain.util;
|
||||
|
||||
import com.baeldung.domain.model.Message;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
|
||||
public class MessageMatcher implements ArgumentMatcher<Message> {
|
||||
|
||||
private Message left;
|
||||
|
||||
public MessageMatcher(Message message) {
|
||||
this.left = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(Message right) {
|
||||
return left.getFrom().equals(right.getFrom()) &&
|
||||
left.getTo().equals(right.getTo()) &&
|
||||
left.getText().equals(right.getText()) &&
|
||||
right.getDate() != null &&
|
||||
right.getId() != null;
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.junit5.mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import com.baeldung.junit5.mockito.repository.MailClient;
|
||||
import com.baeldung.junit5.mockito.repository.SettingRepository;
|
||||
import com.baeldung.junit5.mockito.repository.UserRepository;
|
||||
import com.baeldung.junit5.mockito.service.DefaultUserService;
|
||||
import com.baeldung.junit5.mockito.service.Errors;
|
||||
import com.baeldung.junit5.mockito.service.UserService;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class UserServiceUnitTest {
|
||||
|
||||
UserService userService;
|
||||
SettingRepository settingRepository;
|
||||
@Mock UserRepository userRepository;
|
||||
@Mock MailClient mailClient;
|
||||
|
||||
User user;
|
||||
|
||||
@BeforeEach
|
||||
void init(@Mock SettingRepository settingRepository) {
|
||||
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
||||
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
|
||||
when(settingRepository.getUserNameMinLength()).thenReturn(4);
|
||||
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);
|
||||
this.settingRepository = settingRepository;
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
|
||||
// Given
|
||||
user = new User("Jerry", 12);
|
||||
when(userRepository.insert(any(User.class))).then(new Answer<User>() {
|
||||
int sequence = 1;
|
||||
|
||||
@Override
|
||||
public User answer(InvocationOnMock invocation) throws Throwable {
|
||||
User user = (User) invocation.getArgument(0);
|
||||
user.setId(sequence++);
|
||||
return user;
|
||||
}
|
||||
});
|
||||
|
||||
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
||||
|
||||
// When
|
||||
User insertedUser = userService.register(user);
|
||||
|
||||
// Then
|
||||
verify(userRepository).insert(user);
|
||||
Assertions.assertNotNull(user.getId());
|
||||
verify(mailClient).sendUserRegistrationMail(insertedUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
|
||||
// Given
|
||||
user = new User("tom", 12);
|
||||
|
||||
// When
|
||||
try {
|
||||
userService.register(user);
|
||||
fail("Should give an error");
|
||||
} catch(Exception ex) {
|
||||
assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT);
|
||||
}
|
||||
|
||||
// Then
|
||||
verify(userRepository, never()).insert(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSmallAge_whenSaveUser_thenGiveYoungUserError() {
|
||||
// Given
|
||||
user = new User("jerry", 3);
|
||||
|
||||
// When
|
||||
try {
|
||||
userService.register(user);
|
||||
fail("Should give an error");
|
||||
} catch(Exception ex) {
|
||||
assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG);
|
||||
}
|
||||
|
||||
// Then
|
||||
verify(userRepository, never()).insert(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
|
||||
// Given
|
||||
user = new User("jerry", 12);
|
||||
Mockito.reset(userRepository);
|
||||
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
|
||||
|
||||
// When
|
||||
try {
|
||||
userService.register(user);
|
||||
fail("Should give an error");
|
||||
} catch(Exception ex) {
|
||||
assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE);
|
||||
}
|
||||
|
||||
// Then
|
||||
verify(userRepository, never()).insert(user);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
public final class FinalList extends MyList {
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MockFinals {
|
||||
|
||||
@Test
|
||||
public void whenMockFinalClassMockWorks() {
|
||||
|
||||
FinalList finalList = new FinalList();
|
||||
|
||||
FinalList mock = mock(FinalList.class);
|
||||
when(mock.size()).thenReturn(2);
|
||||
|
||||
assertNotEquals(mock.size(), finalList.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMockFinalMethodMockWorks() {
|
||||
|
||||
MyList myList = new MyList();
|
||||
|
||||
MyList mock = mock(MyList.class);
|
||||
when(mock.finalMethod()).thenReturn(1);
|
||||
|
||||
assertNotEquals(mock.finalMethod(), myList.finalMethod());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user