Mockito endsWith Method

The endsWith method in the Mockito framework is part of the ArgumentMatchers class. It is used to match a String argument that ends with the given suffix. This is particularly useful when you need to verify or stub method calls where the specific string argument should end with a certain suffix.

Table of Contents

  1. Introduction
  2. endsWith Method Syntax
  3. Examples
    • Basic Usage
    • Using endsWith in Different Scenarios
  4. Real-World Use Case
  5. Conclusion

Introduction

Mockito is a popular library in Java for creating and managing mock objects. The endsWith method, which belongs to the ArgumentMatchers class, allows you to specify that a string argument should end with a given suffix. This can be useful for simplifying tests where the specific ending of a string argument is important.

endsWith Method Syntax

Matching a String Argument that Ends with a Given Suffix

import org.mockito.ArgumentMatchers;

static String endsWith(String suffix)

Matches a String argument that ends with the given suffix.

Parameters:

  • suffix: The suffix that the string argument should end with.

Returns:

  • A String that matches the string argument ending with the given suffix.

Examples

Basic Usage

Use endsWith to match a string argument that ends with a given suffix in a mocked method call.

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

public class BasicEndsWithTest {
    @Test
    void testEndsWith() {
        UserService mockUserService = mock(UserService.class);

        // Stub the method to return a specific value
        when(mockUserService.getUserByEmail(ArgumentMatchers.endsWith("@example.com"))).thenReturn("Mock user");

        // Call the method with different string arguments
        String result1 = mockUserService.getUserByEmail("user1@example.com");
        String result2 = mockUserService.getUserByEmail("user2@example.org");

        // Verify the results
        assertEquals("Mock user", result1);
        assertNull(result2);
    }
}

class UserService {
    public String getUserByEmail(String email) {
        return "Real user for email: " + email;
    }
}

Using endsWith in Different Scenarios

Use endsWith to match string arguments in methods with multiple parameters.

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

public class EndsWithWithMultipleParametersTest {
    @Test
    void testEndsWithWithMultipleParameters() {
        NotificationService mockNotificationService = mock(NotificationService.class);

        // Stub the method to return specific values
        when(mockNotificationService.sendNotification(ArgumentMatchers.anyString(), ArgumentMatchers.endsWith(".com"))).thenReturn("Notification sent");

        // Call the method with different arguments
        String result1 = mockNotificationService.sendNotification("Welcome", "user1@example.com");
        String result2 = mockNotificationService.sendNotification("Welcome", "user2@example.org");

        // Verify the results
        assertEquals("Notification sent", result1);
        assertNull(result2);
    }
}

interface NotificationService {
    String sendNotification(String subject, String recipientEmail);
}

Real-World Use Case

Simplifying Tests for Services with String Parameters

In a real-world scenario, you might need to test services with methods that take string parameters where the specific ending of the string is important. Using endsWith can simplify these tests by allowing you to focus on the behavior you are testing rather than the exact content of the strings.

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

interface EmailService {
    void sendEmail(String recipient, String subject, String body);
}

class UserService {
    private final EmailService emailService;

    public UserService(EmailService emailService) {
        this.emailService = emailService;
    }

    public void notifyUser(String userId, String message) {
        // User notification logic
        emailService.sendEmail(userId + "@example.com", "Notification", message);
    }
}

public class UserServiceTest {
    @Test
    void testNotifyUser() {
        EmailService mockEmailService = mock(EmailService.class);
        UserService userService = new UserService(mockEmailService);

        // Call the method
        userService.notifyUser("user123", "Your account has been updated.");

        // Verify the interaction
        verify(mockEmailService).sendEmail(ArgumentMatchers.endsWith("@example.com"), eq("Notification"), anyString());
    }
}

In this example, the UserServiceTest class uses Mockito’s endsWith method to match any string argument that ends with @example.com for the sendEmail method. This simplifies the test by allowing you to verify the interaction based on the ending of the string.

Conclusion

The endsWith method in Mockito is used for matching string arguments that end with a given suffix in mocked method calls. By using endsWith, you can simplify your tests and focus on the behavior you are testing, rather than the exact content of the strings. This helps ensure that your tests are flexible, comprehensive, and easy to maintain.

Leave a Comment

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

Scroll to Top