Static methods

21 views
Skip to first unread message

Stack Philips

unread,
Mar 18, 2025, 12:37:24 PMMar 18
to mockito

Hi, I have a question/problem with static methods in Mockito

I have a class with multiples static method, for example:

public class User{

     public static Boolean isActive(...){...}

     public static Boolean isAdmin(...){...}

     public static Boolean isConnected(...){...}

     public static Boolean checkSecurity(...){

            return isActive(...) && isAdmin(...) && isConnected(...);

     }

}

If we wanted to test the checkSecurity method, with Mockito we would have to mock the results of the isActive, isAdmin and isConnected functions.

If we put:

try(MockedStatic<User> mockedStatic = mockStatic(User.class)) {

    mockedStatic.when(() -> isActive(...)).thenReturn(true);

    mockedStatic.when(() -> isAdmin(...)).thenReturn(true);

    mockedStatic.when(() -> isConnected(...)).thenReturn(true);

    boolean result = checkSecurity(...);
    Assertions.assertTrue(result);

}

The checkSecurity method isn't executed as a normal call, it is executed as a static mock method where parameters aren't passed. The test fails because result is false.

How could this problem be solved?

Reply all
Reply to author
Forward
0 new messages