Mockito mock Method

The mock method in Mockito is used to create mock objects for testing. These mock objects simulate the behavior of real objects, allowing you to test your code without relying on the actual implementations. This is helpful for isolating the unit of code being tested and making your tests more reliable.

Table of Contents

  1. Introduction
  2. mock Method Syntax
  3. Examples
    • Basic Usage
    • Specifying a Mock Name
    • Creating a Mock with Custom Settings
    • Creating a Mock with a Default Answer
  4. Real-World Use Case
  5. Conclusion

Introduction

Mockito is a popular library in Java for creating mock objects. The mock method lets you create mock instances of classes and interfaces. These mocks can be configured to return specific values and to verify interactions. This helps you test your code by replacing real dependencies with mock objects.

mock Method Syntax

Basic Mock Creation

static <T> T mock(Class<T> classToMock)

Creates a mock object of the given class or interface.

Specifying Mock Name

static <T> T mock(Class<T> classToMock, String name)

Creates a mock object and assigns it a name, useful for debugging.

Creating a Mock with Custom Settings

static <T> T mock(Class<T> classToMock, MockSettings mockSettings)

Creates a mock with specified custom settings.

Creating a Mock with a Default Answer

static <T> T mock(Class<T> classToMock, Answer defaultAnswer)

Creates a mock with a specified strategy for its answers to interactions.

Examples

Basic Usage

Create a mock instance of a class or interface.

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

public class BasicMockTest {
    @Test
    void testMock() {
        UserService mockUserService = mock(UserService.class);
        assertNotNull(mockUserService);
    }
}

class UserService {
    public String getUserDetails(String userId) {
        return "User details";
    }
}

Specifying a Mock Name

Create a mock instance with a specified name.

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

public class NamedMockTest {
    @Test
    void testMockWithName() {
        UserService mockUserService = mock(UserService.class, "UserServiceMock");
        assertNotNull(mockUserService);
    }
}

class UserService {
    public String getUserDetails(String userId) {
        return "User details";
    }
}

Creating a Mock with Custom Settings

Create a mock instance with custom settings.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
import org.mockito.MockSettings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class CustomSettingsMockTest {
    @Test
    void testMockWithCustomSettings() {
        MockSettings settings = withSettings().defaultAnswer(invocation -> "Default Answer");
        UserService mockUserService = mock(UserService.class, settings);
        assertNotNull(mockUserService);
    }
}

class UserService {
    public String getUserDetails(String userId) {
        return "User details";
    }
}

Creating a Mock with a Default Answer

Create a mock instance with a default answer strategy.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.RETURNS_SMART_NULLS;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class DefaultAnswerMockTest {
    @Test
    void testMockWithDefaultAnswer() {
        UserService mockUserService = mock(UserService.class, RETURNS_SMART_NULLS);
        assertNotNull(mockUserService);
    }
}

class UserService {
    public String getUserDetails(String userId) {
        return "User details";
    }
}

Real-World Use Case

Testing a UserService Class with UserRepository Dependency

In a real-world scenario, you might have a UserService class that depends on a UserRepository. Using Mockito, you can create a mock of the UserRepository to test UserService in isolation.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class User {
    private String id;
    private String name;

    public User(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

interface UserRepository {
    User findUserById(String id);
}

class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public String getUserName(String userId) {
        User user = userRepository.findUserById(userId);
        return user != null ? user.getName() : null;
    }
}

public class UserServiceTest {
    @Test
    void testGetUserName() {
        UserRepository mockUserRepository = mock(UserRepository.class);
        when(mockUserRepository.findUserById("123")).thenReturn(new User("123", "John Doe"));
        
        UserService userService = new UserService(mockUserRepository);
        String userName = userService.getUserName("123");
        
        assertEquals("John Doe", userName);
        verify(mockUserRepository).findUserById("123");
    }
}

In this example, the UserServiceTest class uses Mockito’s mock method to create a mock instance of the UserRepository interface. The test then configures the mock, calls the method under test, and verifies the behavior and interactions.

Conclusion

The mock method in Mockito is used for creating mock objects to test your code. By using mock, you can simulate the behavior of dependencies, configure mocks to return specific values, and verify interactions. This helps ensure that your tests are reliable and focused on the code under test.

Leave a Comment

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

Scroll to Top