how to mock static method of a class with no return type

Viewed 419

I need to mock a static method of a class which is also void. So, lets say if my class is.

class Util{
public static void test(){}
}

and my Action class which calls Util's method

class Action{
public void update(){
Util.test();
}

}

My test class is:

class Test{
Action action=new Action();
action.update();

//want to 
}

My question is how can I mock a class and verify if its method gets called Util.test(); how can I put something like:

given(Util.test());//in this case I cannot put willReturn as this has type void

3 Answers

You don't; this causes all sorts of problems. Instead, either test the final effects of your static method (though it's best if static methods don't have side effects), or replace your call to the static method with a functional interface such as Runnable or Consumer and pass Util::test to the Action constructor.

You can use the verify() from Mockito this.

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

I don't have the context to suggest refactoring your design to get rid of the static method, or whether it is appropriate according to your use case.

However, you can mock and verify that static methods have been called, using mockito-inline. Here a minimal test that does what you need:

@Test
public void actionShouldCallUtilTest() {
    try (MockedStatic<Util> mockedStatic = mockStatic(Util.class)) {
        // given
        Action action = new Action();

        // when
        action.update();

        // then
        mockedStatic.verify(Util::test);
    }
}

Have a look at the MockedStatic documentation for its features. https://javadoc.io/static/org.mockito/mockito-core/4.3.1/org/mockito/MockedStatic.html

Related