Verify static method calls with Mockito
Asked Answered
F

2

26

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.

Freaky answered 24/8, 2021 at 7:19 Comment(1)
What version of mockito do you use. In 3.5.13 it is not deprecated.Kusin
S
44

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

Servant answered 24/8, 2021 at 7:35 Comment(1)
Just a little improvement. There is a default method on MockedStatic interface default void verify(Verification verification) which calls verify(verification, times(1));Jarad
D
0

Here an example:

void shouldLogInfoAfterRecord() {

    try (MockedStatic<LoggingHelper> loggingHelperMocked = mockStatic(LoggingHelper.class)) {
      kafkaInterceptor.afterRecord(consumerRecord, consumer);
    
      loggingHelperMocked.verify(LoggingHelper::clearContext, times(1));
    }
  }

Note: the method: clearContext has the give signature: public static void clearContext() , And it's executed inside of kafkaInterceptor.afterRecord.

Dorfman answered 1/8 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.