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

Time:12-05

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

CodePudding user response:

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.

CodePudding user response:

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");
  • Related