Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mockito

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.

like image 828
user3552178 Avatar asked Dec 31 '22 23:12

user3552178


1 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())
    );
}
like image 116
Lesiak Avatar answered Jan 13 '23 15:01

Lesiak