How can I properly mock and verify static methods with arguments using `mockedStatic`?

Most examples for mockedStatic in Mockito cover methods without parameters:

mocked.when(Foo::method).thenReturn("bar");
assertEquals("bar", Foo.method());
mocked.verify(Foo::method);

I want to mock a static method that takes parameters, but this approach doesn’t work:

mocked.when(Foo.methodWithParams("SomeValue"));

When a static method has parameters, you need to wrap the call in a lambda to pass it to when(). For example:

try (MockedStatic<Foo> mocked = Mockito.mockStatic(Foo.class)) {
    mocked.when(() -> Foo.methodWithParams("SomeValue")).thenReturn("mockedValue");

    String result = Foo.methodWithParams("SomeValue");
    assertEquals("mockedValue", result);

    mocked.verify(() -> Foo.methodWithParams("SomeValue"));
}

The lambda ensures Mockito knows exactly which method call (with parameters) you want to mock. This approach worked smoothly in my projects.

If you want to mock a static method for any argument, you can combine the lambda with ArgumentMatchers:


import static org.mockito.ArgumentMatchers.anyString;

try (MockedStatic<Foo> mocked = Mockito.mockStatic(Foo.class)) {
    mocked.when(() -> Foo.methodWithParams(anyString())).thenReturn("mockedValue");

    assertEquals("mockedValue", Foo.methodWithParams("Hello"));
    assertEquals("mockedValue", Foo.methodWithParams("World"));
}

This is useful when you don’t care about the exact parameter value and just want the method mocked for all inputs.

Beyond mocking, verifying static method calls with arguments also uses a lambda:

try (MockedStatic<Foo> mocked = Mockito.mockStatic(Foo.class)) {
    mocked.when(() -> Foo.methodWithParams("Test")).thenReturn("mocked");

    Foo.methodWithParams("Test");

    mocked.verify(() -> Foo.methodWithParams("Test"));
}

I like this variation because it keeps mocking and verification consistent, and it avoids common pitfalls like forgetting to use a lambda for parameterized static methods.