🎓 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 never() method in Mockito is used to verify that a certain method on a mock object was never called. This is particularly useful for ensuring that no unwanted interactions have occurred. This tutorial will demonstrate how to use the never() method in Mockito to check that certain method invocations did not happen.
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 NotificationService class that has a dependency on a EmailService. Our goal is to test the NotificationService methods using the never() method in Mockito to ensure that no unwanted interactions with the EmailService occur.
NotificationService and EmailService Classes
First, create the Email class, the EmailService interface, and the NotificationService class.
public class Email {
private String recipient;
private String message;
// Constructor, getters, and setters
public Email(String recipient, String message) {
this.recipient = recipient;
this.message = message;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public interface EmailService {
void sendEmail(Email email);
}
public class NotificationService {
private final EmailService emailService;
public NotificationService(EmailService emailService) {
this.emailService = emailService;
}
public void sendNotification(String recipient, String message) {
// Only send email if recipient and message are not empty
if (recipient != null && !recipient.isEmpty() && message != null && !message.isEmpty()) {
Email email = new Email(recipient, message);
emailService.sendEmail(email);
}
}
}
JUnit 5 Test Class with Mockito
Create a test class for NotificationService 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.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(MockitoExtension.class)
public class NotificationServiceTest {
@Mock
private EmailService emailService;
@InjectMocks
private NotificationService notificationService;
@Test
public void testSendNotification() {
// Given
String recipient = "test@example.com";
String message = "Hello, World!";
// When
notificationService.sendNotification(recipient, message);
// Then
verify(emailService, times(1)).sendEmail(new Email(recipient, message));
}
@Test
public void testSendNotificationNeverCalled() {
// Given
String recipient = "";
String message = "Hello, World!";
// When
notificationService.sendNotification(recipient, message);
// Then
verify(emailService, never()).sendEmail(any(Email.class));
}
@Test
public void testSendNotificationNullRecipient() {
// Given
String recipient = null;
String message = "Hello, World!";
// When
notificationService.sendNotification(recipient, message);
// Then
verify(emailService, never()).sendEmail(any(Email.class));
}
@Test
public void testSendNotificationNullMessage() {
// Given
String recipient = "test@example.com";
String message = null;
// When
notificationService.sendNotification(recipient, message);
// Then
verify(emailService, never()).sendEmail(any(Email.class));
}
}
Explanation
Creating Mocks with
@Mock:- The
@Mockannotation creates a mock instance of theEmailServiceinterface. This mock instance can be used to simulate the behavior of theEmailServicein a controlled way.
- The
Injecting Mocks with
@InjectMocks:- The
@InjectMocksannotation injects the mockEmailServiceinto theNotificationServiceinstance to provide a controlled test environment. This allows theNotificationServicemethods to be tested in isolation from the actualEmailServiceimplementation.
- The
Verifying Interactions with
never():- The
verify(emailService, never()).sendEmail(any(Email.class));method checks if thesendEmailmethod was never called on theEmailServicemock object. This ensures that thesendNotificationmethod of theNotificationServiceclass does not interact with theEmailServicewhen the recipient is empty, null, or when the message is null.
- The
Additional Scenarios
Scenario: Verifying No Interactions
In this scenario, we will demonstrate how to verify that no interactions occurred with the mock object using the verifyNoInteractions() method.
@Test
public void testNoInteractionsWithEmailService() {
// Given
// No interactions expected
// When
// No method calls
// Then
verifyNoInteractions(emailService);
}
Scenario: Verifying Method Never Called with Specific Argument
In this scenario, we will demonstrate how to verify that a method was never called with a specific argument.
@Test
public void testSendNotificationNeverCalledWithSpecificArgument() {
// Given
String recipient = "test@example.com";
String message = "Hello, World!";
// When
notificationService.sendNotification(recipient, "");
// Then
verify(emailService, never()).sendEmail(new Email(recipient, message));
}
Conclusion
The never() method in Mockito simplifies the verification that certain method calls on mock objects did not occur. By using never(), you can ensure that your code does not interact with dependencies in unwanted ways. This step-by-step guide demonstrated how to effectively use the never() method in your unit tests, covering different scenarios to ensure comprehensive testing of the NotificationService 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