Mockito mockStatic Method

The mockStatic method in the Mockito framework is used to create a thread-local mock controller for all static methods of a given class or interface. This allows you to mock static methods, providing fine-grained control over the behavior of these methods during testing.

Table of Contents

  1. Introduction
  2. mockStatic Method Syntax
  3. Examples
    • Basic Usage
    • Using Custom Mock Settings
    • Using a Custom Answer
  4. Real-World Use Case
  5. Conclusion

Introduction

Mockito is a popular library in Java for creating and managing mock objects. The mockStatic method, which belongs to the Mockito class, allows you to mock static methods of a class or interface. This can be useful when you need to control the behavior of static methods during testing, ensuring that they return expected results.

mockStatic Method Syntax

Creating a Basic Mock Controller for Static Methods

import static org.mockito.Mockito.mockStatic;

static <T> MockedStatic<T> mockStatic(Class<T> classToMock)

Creates a thread-local mock controller for all static methods of the given class or interface.

Using a Custom Name

import static org.mockito.Mockito.mockStatic;

static <T> MockedStatic<T> mockStatic(Class<T> classToMock, String name)

Creates a thread-local mock controller for all static methods of the given class or interface with a custom name.

Using Custom Mock Settings

import static org.mockito.Mockito.mockStatic;
import org.mockito.MockSettings;

static <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings mockSettings)

Creates a thread-local mock controller for all static methods of the given class or interface with custom mock settings.

Using a Custom Answer

import static org.mockito.Mockito.mockStatic;
import org.mockito.stubbing.Answer;

static <T> MockedStatic<T> mockStatic(Class<T> classToMock, Answer defaultAnswer)

Creates a thread-local mock controller for all static methods of the given class or interface with a custom answer.

Examples

Basic Usage

Mock the static methods of a simple class.

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

public class BasicMockStaticTest {
    @Test
    void testMockStatic() {
        try (MockedStatic<MathUtils> mockedStatic = mockStatic(MathUtils.class)) {
            when(MathUtils.add(1, 2)).thenReturn(5);

            int result = MathUtils.add(1, 2);
            assertEquals(5, result);
        }
    }
}

class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }
}

Using Custom Mock Settings

Mock the static methods of a class with custom mock settings.

import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.withSettings;
import static org.mockito.Mockito.when;
import org.mockito.MockedStatic;
import org.mockito.MockSettings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CustomMockSettingsTest {
    @Test
    void testMockStaticWithSettings() {
        MockSettings mockSettings = withSettings().defaultAnswer(invocation -> "Default Answer");

        try (MockedStatic<MathUtils> mockedStatic = mockStatic(MathUtils.class, mockSettings)) {
            when(MathUtils.add(1, 2)).thenReturn(5);

            int result = MathUtils.add(1, 2);
            assertEquals(5, result);

            String defaultAnswer = MathUtils.someOtherStaticMethod();
            assertEquals("Default Answer", defaultAnswer);
        }
    }
}

class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }

    public static String someOtherStaticMethod() {
        return "Real Answer";
    }
}

Using a Custom Answer

Mock the static methods of a class with a custom answer.

import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import org.mockito.MockedStatic;
import org.mockito.stubbing.Answer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CustomAnswerTest {
    @Test
    void testMockStaticWithCustomAnswer() {
        Answer<Integer> customAnswer = invocation -> 42;

        try (MockedStatic<MathUtils> mockedStatic = mockStatic(MathUtils.class, customAnswer)) {
            when(MathUtils.add(1, 2)).thenReturn(5);

            int result = MathUtils.add(1, 2);
            assertEquals(5, result);

            int customResult = MathUtils.multiply(2, 3);
            assertEquals(42, customResult);
        }
    }
}

class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }
}

Real-World Use Case

Mocking Static Utility Methods in a Complex Application

In a real-world scenario, you might want to mock static utility methods in a complex application to control their behavior during testing. This can help ensure that the static methods return the expected results and do not interfere with the test outcomes.

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

class OrderService {
    public int calculateTotal(int price, int quantity) {
        return MathUtils.add(price, quantity) + MathUtils.calculateTax(price);
    }
}

class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }

    public static int calculateTax(int price) {
        return (int) (price * 0.1);
    }
}

public class OrderServiceTest {
    @Test
    void testOrderServiceWithMockedMathUtils() {
        try (MockedStatic<MathUtils> mockedStatic = mockStatic(MathUtils.class)) {
            when(MathUtils.add(100, 2)).thenReturn(102);
            when(MathUtils.calculateTax(100)).thenReturn(10);

            OrderService orderService = new OrderService();
            int total = orderService.calculateTotal(100, 2);

            assertEquals(112, total);
        }
    }
}

In this example, the OrderServiceTest class uses Mockito’s mockStatic method to mock the static methods of the MathUtils class. This allows the test to control the behavior of the MathUtils methods and ensure that the OrderService calculates the total correctly.

Conclusion

The mockStatic method in Mockito is used for creating thread-local mock controllers for all static methods of a given class or interface. By using mockStatic, you can control the behavior of static methods during testing, ensuring that they return expected results. 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