Mockito thenReturn Method

The thenReturn method in the Mockito framework is used to set return values for stubbed methods. This allows you to define specific values that should be returned when the method is called. The method belongs to the OngoingStubbing interface, which is used to configure the behavior of mock methods.

Table of Contents

  1. Introduction
  2. thenReturn Method Syntax
  3. Examples
    • Basic Usage
    • Setting Consecutive Return Values
  4. Real-World Use Case
  5. Conclusion

Introduction

Mockito is a popular library in Java for creating and managing mock objects. The thenReturn method, which belongs to the OngoingStubbing interface, allows you to specify return values for stubbed methods. This can be useful when you need to control the behavior of a method and ensure it returns specific values during testing.

thenReturn Method Syntax

Setting a Single Return Value

import org.mockito.stubbing.OngoingStubbing;

OngoingStubbing<T> thenReturn(T value)

Sets a single return value to be returned when the method is called.

Setting Consecutive Return Values

import org.mockito.stubbing.OngoingStubbing;

OngoingStubbing<T> thenReturn(T value, T... values)

Sets consecutive return values to be returned when the method is called.

Parameters:

  • value: The first value to be returned.
  • values: Additional values to be returned consecutively on subsequent calls.

Returns:

  • An OngoingStubbing object that allows further configuration of the stubbed method.

Examples

Basic Usage

Set a single return value for a stubbed method.

import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class BasicThenReturnTest {
    @Test
    void testThenReturn() {
        UserService mockUserService = mock(UserService.class);

        // Set a return value
        when(mockUserService.getUserDetails(anyString())).thenReturn("Mock user details");

        // Call the method
        String details = mockUserService.getUserDetails("123");
        assertEquals("Mock user details", details);
    }
}

class UserService {
    public String getUserDetails(String userId) {
        return "Real user details for " + userId;
    }
}

Setting Consecutive Return Values

Set consecutive return values for a stubbed method.

import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class ConsecutiveThenReturnTest {
    @Test
    void testConsecutiveThenReturn() {
        UserService mockUserService = mock(UserService.class);

        // Set consecutive return values
        when(mockUserService.getUserDetails(anyString())).thenReturn("First call", "Second call", "Third call");

        // Call the method multiple times
        String firstCall = mockUserService.getUserDetails("123");
        String secondCall = mockUserService.getUserDetails("123");
        String thirdCall = mockUserService.getUserDetails("123");

        // Verify the results
        assertEquals("First call", firstCall);
        assertEquals("Second call", secondCall);
        assertEquals("Third call", thirdCall);
    }
}

class UserService {
    public String getUserDetails(String userId) {
        return "Real user details for " + userId;
    }
}

Real-World Use Case

Mocking a Service with Multiple States

In a real-world scenario, you might need to mock a service that returns different values based on its state or the number of times a method is called. The thenReturn method allows you to define these consecutive return values easily.

import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

interface PaymentService {
    String processPayment(String orderId);
}

class PaymentServiceImpl implements PaymentService {
    public String processPayment(String orderId) {
        // Real implementation
        return "Processing payment for order " + orderId;
    }
}

public class PaymentServiceTest {
    @Test
    void testProcessPayment() {
        PaymentService mockPaymentService = mock(PaymentService.class);

        // Set consecutive return values
        when(mockPaymentService.processPayment(anyString())).thenReturn("Payment initiated", "Payment processing", "Payment completed");

        // Call the method multiple times
        String firstCall = mockPaymentService.processPayment("123");
        String secondCall = mockPaymentService.processPayment("123");
        String thirdCall = mockPaymentService.processPayment("123");

        // Verify the results
        assertEquals("Payment initiated", firstCall);
        assertEquals("Payment processing", secondCall);
        assertEquals("Payment completed", thirdCall);
    }
}

In this example, the PaymentServiceTest class uses Mockito’s thenReturn method to mock the processPayment method with consecutive return values. This allows the test to simulate different states of the payment process and verify that the service behaves as expected under different conditions.

Conclusion

The thenReturn method in Mockito is used for setting return values for stubbed methods. By using thenReturn, you can define specific return values for a method and even set consecutive return values for multiple calls. This helps ensure that your tests are accurate and comprehensive, allowing you to validate both real and mocked behavior.

Leave a Comment

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

Scroll to Top