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.
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())
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With