I have class let say ABC. In this class there is static method public static void staticOne(){...} In same class there are non-static methods also present let say method1() method2().

In mockito I want to write test case for method1() in which static method staticOne is being called and I want to mock it. So how can I do that ?

I am using mockito version 4.11.0. Can I have solution for this problem using only mockito ?

=============================================================

class ABC {

public void static staticOne(){
...
}

public string method1(){
staticOne();
...
}

}

how can I write test case for method1() while mocking staticOne

1

There are 1 best solutions below

1
WLefever On

Although it's possible, I wouldn't recommend it. There might be a way to refactor and split the static method out into a util class.

If it's not possible you can use MockStatic and afterwards create an instance :

MockedStatic<ABC> staticABC = Mockito.mockStatic(ABC.class);
... // define operations on mock
ABC abc = new ABC();
abc.method1();
... // assertions

I added an example in this repository