🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The mock() method in Mockito is used to create mock objects for unit testing. Mock objects simulate the behavior of real objects in a controlled way, allowing you to isolate the code under test. This tutorial will demonstrate how to use the mock() method in Mockito to create and configure mock objects.
Maven Dependencies
To use Mockito with JUnit 5, add the following dependencies to your pom.xml file:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
Example Scenario
We will create a UserService class that has a dependency on a UserRepository. Our goal is to test the UserService methods using the mock() method in Mockito to create mock objects for the dependencies.
UserService and UserRepository Classes
First, create the User class, the UserRepository interface, and the UserService class.
public class User {
private String name;
private String email;
// Constructor, getters, and setters
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public interface UserRepository {
void saveUser(User user);
User findUserByEmail(String email);
}
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void registerUser(String name, String email) {
User user = new User(name, email);
userRepository.saveUser(user);
}
public User getUserByEmail(String email) {
return userRepository.findUserByEmail(email);
}
}
JUnit 5 Test Class with Mockito
Create a test class for UserService using JUnit 5 and Mockito.
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
public class UserServiceTest {
@Test
public void testRegisterUser() {
// Create a mock UserRepository
UserRepository userRepository = mock(UserRepository.class);
// Create a UserService with the mock UserRepository
UserService userService = new UserService(userRepository);
// Given
String name = "John Doe";
String email = "john.doe@example.com";
// When
userService.registerUser(name, email);
// Then
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
verify(userRepository).saveUser(userCaptor.capture());
User capturedUser = userCaptor.getValue();
assertEquals(name, capturedUser.getName());
assertEquals(email, capturedUser.getEmail());
}
@Test
public void testGetUserByEmail() {
// Create a mock UserRepository
UserRepository userRepository = mock(UserRepository.class);
// Create a UserService with the mock UserRepository
UserService userService = new UserService(userRepository);
// Given
String email = "jane.doe@example.com";
User mockUser = new User("Jane Doe", email);
when(userRepository.findUserByEmail(email)).thenReturn(mockUser);
// When
User result = userService.getUserByEmail(email);
// Then
assertNotNull(result);
assertEquals("Jane Doe", result.getName());
assertEquals(email, result.getEmail());
verify(userRepository).findUserByEmail(email);
}
}
Explanation
Creating Mocks with
mock():- The
mock(UserRepository.class)method creates a mock instance of theUserRepositoryinterface. - This mock instance can be used to simulate the behavior of the
UserRepositoryin a controlled way.
- The
Injecting Mocks:
- The mock
UserRepositoryis injected into theUserServiceconstructor to provide a controlled test environment. - This allows the
UserServicemethods to be tested in isolation from the actualUserRepositoryimplementation.
- The mock
Configuring Mock Behavior:
- The
when(userRepository.findUserByEmail(email)).thenReturn(mockUser)method configures the mockUserRepositoryto return a predefinedUserobject when thefindUserByEmailmethod is called with the specified email.
- The
Verifying Interactions:
- The
verify(userRepository).saveUser(userCaptor.capture())method verifies that thesaveUsermethod was called on theUserRepositorywith aUserobject. - The
ArgumentCaptorcaptures theUserobject passed to thesaveUsermethod, allowing for further assertions on its properties. - The
verify(userRepository).findUserByEmail(email)method verifies that thefindUserByEmailmethod was called on theUserRepositorywith the specified email.
- The
Conclusion
The mock() method in Mockito simplifies the creation of mock objects for unit testing. By using mock(), you can easily simulate dependencies and test the behavior of your code in isolation. This step-by-step guide demonstrated how to effectively use the mock() method in your unit tests, covering different scenarios to ensure comprehensive testing of the UserService class.
Related Mockito Methods
Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers
Comments
Post a Comment
Leave Comment