For working professionals
For fresh graduates
More
1. Introduction
6. PyTorch
9. AI Tutorial
10. Airflow Tutorial
11. Android Studio
12. Android Tutorial
13. Animation CSS
16. Apex Tutorial
17. App Tutorial
18. Appium Tutorial
21. Armstrong Number
22. ASP Full Form
23. AutoCAD Tutorial
27. Belady's Anomaly
30. Bipartite Graph
35. Button CSS
39. Cobol Tutorial
46. CSS Border
47. CSS Colors
48. CSS Flexbox
49. CSS Float
51. CSS Full Form
52. CSS Gradient
53. CSS Margin
54. CSS nth Child
55. CSS Syntax
56. CSS Tables
57. CSS Tricks
58. CSS Variables
61. Dart Tutorial
63. DCL
65. DES Algorithm
83. Dot Net Tutorial
86. ES6 Tutorial
91. Flutter Basics
92. Flutter Tutorial
95. Golang Tutorial
96. Graphql Tutorial
100. Hive Tutorial
103. Install Bootstrap
107. Install SASS
109. IPv 4 address
110. JCL Programming
111. JQ Tutorial
112. JSON Tutorial
113. JSP Tutorial
114. Junit Tutorial
115. Kadanes Algorithm
116. Kafka Tutorial
117. Knapsack Problem
118. Kth Smallest Element
119. Laravel Tutorial
122. Linear Gradient CSS
129. Memory Hierarchy
133. Mockito tutorial
134. Modem vs Router
135. Mulesoft Tutorial
136. Network Devices
138. Next JS Tutorial
139. Nginx Tutorial
141. Octal to Decimal
142. OLAP Operations
143. Opacity CSS
144. OSI Model
145. CSS Overflow
146. Padding in CSS
148. Perl scripting
149. Phases of Compiler
150. Placeholder CSS
153. Powershell Tutorial
158. Pyspark Tutorial
161. Quality of Service
162. R Language Tutorial
164. RabbitMQ Tutorial
165. Redis Tutorial
166. Redux in React
167. Regex Tutorial
170. Routing Protocols
171. Ruby On Rails
172. Ruby tutorial
173. Scala Tutorial
175. Shadow CSS
178. Snowflake Tutorial
179. Socket Programming
180. Solidity Tutorial
181. SonarQube in Java
182. Spark Tutorial
189. TCP 3 Way Handshake
190. TensorFlow Tutorial
191. Threaded Binary Tree
196. Types of Queue
197. TypeScript Tutorial
198. UDP Protocol
202. Verilog Tutorial
204. Void Pointer
205. Vue JS Tutorial
206. Weak Entity Set
207. What is Bandwidth?
208. What is Big Data
209. Checksum
211. What is Ethernet
214. What is ROM?
216. WPF Tutorial
217. Wireshark Tutorial
218. XML Tutorial
Unit testing is a software testing method where individual units or components of an application are tested in isolation. The purpose is to validate that each unit functions as intended. Unit testing has numerous benefits, like it improves code quality, catches bugs early in development, allows safe refactoring of code and provides documentation of code. However, some units may have dependencies on other objects and components. This makes unit testing more difficult. This is where mocking comes in. This Mockito tutorial covers it in detail.
Mockito is one of the most popular mocking frameworks for Java. In this Mockito tutorial, we'll learn the basics of Mockito, its useful features and best practices. We will make the learning process easy with Mockito examples.
By the end of this Mockito tutorial, you'll understand how to use Mockito to unit test your Java code effectively.
Mockito is an open-source mocking framework for Java, commonly referred to as the Mockito framework. It was originally created by Szczepan Faber and Philipp Haselwandter as a fork of EasyMock. Mockito simulates the behavior of real objects in automated unit tests.
This comprehensive Mockito JUnit tutorial details how Mockito helps to effectively test a code, especially when integrating with tools like Mockito Maven and Mockito Spring Boot.
In summary, Mockito provides a simple yet powerful API for configuring mock objects and leveraging them in unit tests.
Before jumping into Mockito, let's briefly discuss unit testing. JUnit is the most common Java unit testing framework. Mockito vs. JUnit is often a topic of discussion. Here is a simple unit test written with JUnit:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
int sum = calculator.add(2, 3);
assertEquals(5, sum);
}
}
This test validates the add() method of a Calculator class by:
JUnit provides the annotations and assertions to write and run unit tests quickly. However, if the Calculator class had dependencies, they would need to be handled for true unit testing. This is where Mockito comes in.
Mocking involves creating fake implementations of dependencies and injecting them into the code under test. In a real application, classes often depend on other classes and interfaces. For example, consider a UserService class that depends on a UserRepository interface:
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void register(String email, String password) {
User user = userRepository.findByEmail(email);
if (user != null) {
throw new RuntimeException("Email already exists");
}
// Save user
}
}
The UserService depends on the UserRepository to check if a user email already exists when registering a new account.
To properly unit test the register() method in isolation, we need to provide a mock UserRepository somehow. This allows us to simulate test scenarios like:
Without mocking, unit testing the UserService would require integration with a real UserRepository implementation like a database. That leads to slower and more brittle tests.
Let's explore some key Mockito concepts.
A mock object is a fake implementation of a real interface or class that allows predefined output to simulated method calls. Mockito allows mocking interfaces to inject a fake implementation for testing.
UserRepository mockUserRepository = Mockito.mock(UserRepository.class);
Real implementations are avoided so that tests run quickly in isolation without external dependencies.
Once mock objects are created, they need to be injected into the code under test. This allows replacing real dependencies with mocks so that their behavior can be controlled.
@Test
public void registerNewUserTest() {
UserRepository mockUserRepo = Mockito.mock(UserRepository.class);
UserService userService = new UserService(mockUserRepo);
// ...
}
Stubbing a method configures it to return a specific value when called during a test:
Mockito.when(mockUserRepo.findByEmail(anyString())).thenReturn(null);
The stub causes findByEmail() to always return null. This is useful for simulating a new user registration scenario.
Mockito verifies that methods were called with expected parameters:
Mockito.verify(mockUserRepo).findByEmail("test@example.com");
This asserts that findByEmail() was called during the test with the email "test@example.com".
There are many advantages of using Mockito for mocks in JUnit tests:
In summary, Mockito makes unit testing Java applications faster, easier and more robust.
Let's explore Mockito syntax and APIs. The key static methods of the Mockito class include:
Here is an example mock:
// Import Mockito library
import static org.mockito.Mockito.*;
// Create mock
UserRepository mockUserRepo = mock(UserRepository.class);
// Stub method
when(mockUserRepo.findByEmail("test@example.com")).thenReturn(null);
// Use mock in test
UserService userService = new UserService(mockUserRepo);
userService.register("test@example.com", "pwd");
// Verify interaction
verify(mockUserRepo).findByEmail("test@example.com");
This demonstrates the essential Mockito workflow:
Now, let's explore some key Mockito capabilities in more detail.
Mockito allows the mocking of both classes and interfaces.
To mock an interface:
List mockList = mock(List.class);
To mock a class:
LinkedList mockList = mock(LinkedList.class);
The mocked instances do not contain any actual code implementation. They can be injected and stubbed as needed in tests.
Mockito includes a variety of matchers to verify that methods were called with the correct parameters.
For example:
//Verify with exact string
verify(mockList).add("Hello");
//Verify with any string
verify(mockList).add(anyString());
//Verify with contains string
verify(mockList).add(contains("World"));
Common matchers include anyInt(), eq(), contains() and more. They provide flexibility in verifying parameter values.
The Mockito when() method allows stubbing a mock method to return a specified value:
when(mockList.size()).thenReturn(5);
int size = mockList.size(); //Returns 5
This configures all calls to mockList.size() to return 5 without a real implementation.
Exceptions can be thrown from stubbed methods via doThrow():
doThrow(new RuntimeException()).when(mockList).clear();
mockList.clear(); //Throws RuntimeException
This can be useful for testing exception-handling logic.
Interactions with mock objects can be verified using verify():
verify(mockList).add("Test");
verify(mockList, times(2)).add(anyString());
This validates that add() was called with expected parameters at least once or a specific number of times.
By default, Mockito verifies mocks in any order. The InOrder API allows verifying sequential interactions:
InOrder inOrder = inOrder(mock1, mock2);
inOrder.verify(mock1).method1();
inOrder.verify(mock2).method2();
This asserts that method1() was called before method2().
Mockito provides annotations for simplifying mocks and stubs. For those working with Spring, Mockito spring boot integration can be particularly useful:
@Mock
List mockList;
@InjectMocks
MyClassUnderTest instance;
@Test
public void myTest() {
// MockList injected into instance
}
The @Mock annotation auto-creates a mock while @InjectMocks injects it into the test instance.
Here are some best practices for Mockito:
Following these practices results in focused, maintainable and robust unit tests.
Let's look at a complete example of using Mockito for a JUnit test.
We'll test a MessageService that uses a NotificationGateway interface:
public class MessageService {
private NotificationGateway notificationGateway;
public MessageService(NotificationGateway notificationGateway) {
this.notificationGateway = notificationGateway;
}
public void sendMessage(String message) {
// Send message
notificationGateway.send(message);
}
}
public interface NotificationGateway {
void send(String message);
}
Here is how this can be unit-tested with mocks:
@Test
public void testSendMessage() {
//Create mock
NotificationGateway gateway = Mockito.mock(NotificationGateway.class);
//Create service with mock
MessageService service = new MessageService(gateway);
//Call method under test
service.sendMessage("Hello World");
//Verify interaction with mock
verify(gateway).send("Hello World");
}
Key steps:
This shows how mocks allow us to unit test MessageService in isolation without coupling it to any messaging infrastructure during the test.
Some examples of what you can test using Mockito:
In summary, Mockito makes tests clean and fast by removing external dependencies. Mocks improve test coverage, increase the speed and reliability of tests, and the design of code.
This Mockito documentation is a valuable resource for students to get more detailed insights on Mockito. We have covered the rationale behind mocking in unit tests, the method to create, inject and configure mocks, useful Mockito features, mocking best practices and a full Mockito example. Mockito removes dependencies that make testing difficult and slows down development. It promotes good design principles and test-driven development. Happy mocking with Mockito!
1. What are some key facts about Mockito?
Key things to know about Mockito are:
2. What are some of the key features and capabilities of Mockito?
Some of the features and capabilities of Mockito include:
3. What is the difference between @Mock and @InjectMocks?
The @Mock annotation is used to create a mock. The @InjectMocks creates an instance of the class and injects the mocks that were created with the @Mock annotation into this instance.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.