Sample codes for mocking a static with Mockito.

The StringUtil class is a very trivial class that converts the text to all capitalized.

StringUtil class

public final class StringUtil {

    private StringUtil() {}

    public static String upperCase(String text) {
        return text.toUpperCase();
    }
}

Mocking the StringUtil.upperCase method

Stubbing the StringUtil.upperCase method to return test if test is passed as argument.

Dependencies Required

org.junit.jupiter:junit-jupiter-engine:5.8.2
org.mockito:mockito-inline:4.4.0

StringUtilTest class

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

public class StringUtilTest {

    @Test
    void staticMethod() {
        try (var utilities = mockStatic(StringUtil.class)) {
            utilities.when(() -> StringUtil.upperCase("test")).thenReturn("test");
            assertEquals("test", StringUtil.upperCase("test"));
        }
    }
}