How to use MockedStatic verify on static methods?

I’m trying to understand how to properly use MockedStatic verify in JUnit to test static method calls. In my case, methods like LoggingUtils.error() and UnitConversion.isCompatible() are invoked inside the service layer. Even though breakpoints confirm these static methods are called, the test still shows a “Wanted but not invoked” error. Should I place the static verification within the same try block where the mock is defined, or should the service method be invoked inside that block? How can I correctly verify static invocations using MockedStatic verify without relying on tools like PowerMock?

Alright, speaking from a few years of wrestling with Mockito the key thing with mockedstatic verify is scope. Static mocks only exist inside the try-with-resources block where they are created. If verification is done after that block, Mockito has already stopped listening, which is why you see “Wanted but not invoked”.

try (MockedStatic<LoggingUtils> loggingMock = Mockito.mockStatic(LoggingUtils.class)) {

    myService.doSomething(); // triggers LoggingUtils.error("msg")

    loggingMock.verify(() -> LoggingUtils.error("msg")); // ✅ works here
}

The rule is simple: **mock + call + mockedstatic verify → all inside the same block. Once the block ends, the mock is gone so verification outside it will always fail.

Let me extend what @akanshasrivastava.1121 said because another common gotcha is ordering. Even if you place mockedstatic verify inside the right block, the test still fails if the method under test runs before the mock is created.

try (MockedStatic<UnitConversion> conversionMock = Mockito.mockStatic(UnitConversion.class)) {

    when(UnitConversion.isCompatible(any(), any())).thenReturn(true);

    myService.processUnits(); // ✅ must happen AFTER mock creation

    conversionMock.verify(() -> UnitConversion.isCompatible(any(), any()), times(1));
}

So the sequence is:

:one: create static mock

:two: stub if necessary

:three: call the actual service

:four: do mockedstatic verify

Reverse the order, and Mockito won’t intercept anything.

Let me add one more layer to @kumari_babitaa’s explanation, when mockedstatic verify still fails even inside the block and in the correct order, 9/10 times it’s the arguments.

Static verification in Mockito matches exact arguments unless you use matchers:

conversionMock.verify(() -> UnitConversion.isCompatible(eq("KG"), any()));

So keep these in mind:

:heavy_check_mark: Use any(), eq(), etc., if the method takes dynamic values

:heavy_check_mark: Never mock in one block and verify in another — mock scope doesn’t carry over

:heavy_check_mark: If you’re verifying times(n), use times() right in the verify call

Basically: the more precise the arguments, the more reliable your mockedstatic verify will be.