Mockito times method

The times method in the Mockito framework is used to verify that a method on a mock object was called exactly a specified number of times. This method is useful when you want to ensure that a method is invoked an exact number of times during the execution of your code.

Table of Contents

  1. Introduction
  2. times Method Syntax
  3. Examples
    • Basic Usage
    • Verifying Multiple Mocks
  4. Real-World Use Case
  5. Conclusion

Introduction

Mockito is a popular library in Java for creating and managing mock objects. The times method, which belongs to the Mockito class, allows you to specify that a method should be called exactly the given number of times on a mock object. This can help ensure that your code performs the expected number of operations.

times Method Syntax

Verifying an Exact Number of Invocations

import static org.mockito.Mockito.times;

static VerificationMode times(int wantedNumberOfInvocations)

Specifies that a method should have been called exactly the given number of times.

Parameters:

  • wantedNumberOfInvocations: The exact number of times the method should have been called.

Returns:

  • A VerificationMode object that can be used to verify the method calls.

Examples

Basic Usage

Verify that a method was called exactly a specified number of times on a single mock object.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import org.junit.jupiter.api.Test;

public class BasicTimesTest {
    @Test
    void testTimes() {
        UserService mockUserService = mock(UserService.class);

        // Perform some interactions
        mockUserService.deleteUser("123");
        mockUserService.deleteUser("123");

        // Verify that deleteUser was called exactly twice
        verify(mockUserService, times(2)).deleteUser("123");
    }
}

class UserService {
    public void deleteUser(String userId) {
        // Method implementation
    }
}

Verifying Multiple Mocks

Verify that methods were called exactly the specified number of times on multiple mock objects.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import org.junit.jupiter.api.Test;

public class MultipleTimesTest {
    @Test
    void testTimesMultipleMocks() {
        UserService mockUserService = mock(UserService.class);
        NotificationService mockNotificationService = mock(NotificationService.class);

        // Perform some interactions
        mockUserService.deleteUser("123");
        mockUserService.deleteUser("123");

        mockNotificationService.sendNotification("User 123 deleted");
        mockNotificationService.sendNotification("User 123 deleted");

        // Verify that deleteUser was called exactly twice
        verify(mockUserService, times(2)).deleteUser("123");

        // Verify that sendNotification was called exactly twice
        verify(mockNotificationService, times(2)).sendNotification("User 123 deleted");
    }
}

class UserService {
    public void deleteUser(String userId) {
        // Method implementation
    }
}

interface NotificationService {
    void sendNotification(String message);
}

Real-World Use Case

Ensuring Exact Method Calls in a Service

In a real-world scenario, you might want to ensure that certain methods in your service are called exactly a specified number of times. This can help in validating that your code performs the correct number of operations.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import org.junit.jupiter.api.Test;

interface PaymentService {
    void processPayment(String orderId);
}

interface NotificationService {
    void sendNotification(String message);
}

class OrderService {
    private final PaymentService paymentService;
    private final NotificationService notificationService;

    public OrderService(PaymentService paymentService, NotificationService notificationService) {
        this.paymentService = paymentService;
        this.notificationService = notificationService;
    }

    public void placeOrder(String orderId) {
        paymentService.processPayment(orderId);
        notificationService.sendNotification("Order " + orderId + " placed");
    }

    public void processMultiplePayments(String orderId, int times) {
        for (int i = 0; i < times; i++) {
            paymentService.processPayment(orderId);
        }
    }
}

public class OrderServiceTest {
    @Test
    void testOrderServiceInteractionsTimes() {
        PaymentService mockPaymentService = mock(PaymentService.class);
        NotificationService mockNotificationService = mock(NotificationService.class);
        OrderService orderService = new OrderService(mockPaymentService, mockNotificationService);

        // Call methods on OrderService
        orderService.processMultiplePayments("123", 3);

        // Verify that processPayment was called exactly three times
        verify(mockPaymentService, times(3)).processPayment("123");

        // Call another method on OrderService
        orderService.placeOrder("456");

        // Verify that processPayment was called exactly once
        verify(mockPaymentService, times(1)).processPayment("456");

        // Verify that sendNotification was called exactly once
        verify(mockNotificationService, times(1)).sendNotification("Order 456 placed");
    }
}

In this example, the OrderServiceTest class uses Mockito’s times method to ensure that processPayment is called exactly three times and sendNotification is called exactly once. This helps ensure that the OrderService methods perform the correct number of operations.

Conclusion

The times verification mode in Mockito is used for ensuring that methods on mock objects are called exactly the specified number of times. By using times, you can validate that your code performs the correct number of operations, improving the accuracy and reliability of your tests. This helps ensure that your code behaves as expected and performs optimally.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top