All examples of mockedStatic() in Mockito show how to mock methods without parameters. However, when trying to mock a static method that takes arguments, such as Foo.methodWithParams("SomeValue"), it doesn’t seem to work. Is there a correct way to mock static methods that accept parameters in Mockito?
Yes, you can mock static methods with parameters using mockedStatic(). The trick is to use the when method and match arguments using either exact values or ArgumentMatchers. For example:
try (MockedStatic<Foo> mocked = Mockito.mockStatic(Foo.class)) {
mocked.when(() -> Foo.methodWithParams("SomeValue")).thenReturn("MockedResult");
String result = Foo.methodWithParams("SomeValue"); // returns "MockedResult"
}
If you want to handle any value for the parameter, you can use Mockito.any(): `` mocked.when(() → Foo.methodWithParams(Mockito.anyString())).thenReturn(“MockedResult”);
This approach works for methods with one or multiple parameters.
Yep, exactly, mockedStatic() works with parameters. I ran into the same confusion at first. One tip: always wrap the static mocking in a try-with-resources block; otherwise, Mockito may not restore the original behavior, which can cause tests to fail unpredictably.
a useful trick: if you need to verify that the static method was called with specific arguments, you can do this:
mocked.verify(() -> Foo.methodWithParams("SomeValue"), Mockito.times(1));
This lets you both mock the return value and verify the call, which is handy for more complex test scenarios.