Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to verify a public class's static method get called using mockito?

Writer Matthew Harrington

The pseudo code is like this

rc = SomePublicClass.myPublicStaticFunc(arg)
public class SomePublicClass { private SomePublicClass() { } public static int myPublicStaticFunc(arg) { return 5; }
}

in UT this doesn't work

verify(SomePublicClass, times(1)). myPublicStaticFunc();

since this is a public class, how to verify myFunc gets called in mockito in unit test ? If SomePublicClass were a mocked class, this can work.

4

2 Answers

Mocking static methods is available since Mockito 3.4.

See pull request: Mockito #1013: Defines and implements API for static mocking.

Please note that the fact that this feature is available is not equivalent with recommendation to use it. It is aimed at legacy apps where you cannot refactor the source code.

Having said that:

Test when static method takes no arguments:

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

Test when static methods takes arguments:

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()) );
}
2

Since Mockito-Inline 4.0 the order of parameters for verify has been reversed to match the other verification methods:

Test when static method takes no arguments:

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

Test when static methods takes arguments:

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( () -> SomePublicClass.myPublicStaticFunc(anyInt()), times(1) );
}
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy