Search code examples
javaunit-testingtestingmockitostatic-methods

Verify static method calls with Mockito


I am trying to verify in a test that a static method is called. I am using Mockito for this purpose.

This question is similar to this. However, the solution suggested in the most upvoted reply is not applicable anymore as the MockedStatic verify method is deprecated.

try (MockedStatic<SomePublicClass> dummyStatic = Mockito.mockStatic(SomePublicClass.class)) {
dummyStatic.when(() -> SomePublicClass.myPublicStaticFunc(anyInt()))
           .thenReturn(5);
// when
System.out.println(SomePublicClass.myPublicStaticFunc(7));
//then
dummyStatic.verify(
        times(1), 
        () -> SomePublicClass.myPublicStaticFunc(anyInt())
);
}

The alternative is to call

verify(dummyStatic).myPublicStaticFunc(anyInt);

However, it complains that the method myPublicStaticFunc(int) is undefined for the type MockedStatic.

What are my alternatives, or what am I missing. Also, I know I can try this using PowerMock, but for the moment, I am trying to get this working using Mockito only.


Solution

  • It seems that deprecated is void verify(VerificationMode mode, Verification verification) while void verify(Verification verification, VerificationMode mode) is still fine so you can just use the verify method like

    dummyStatic.verify(
        () -> SomePublicClass.myPublicStaticFunc(anyInt()),
        times(1)
    );
    

    I've used the following dependency: testImplementation "org.mockito:mockito-inline:3.12.1".

    It seems that with mockito-core you will not be able to mock this because you'll receive

    The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks