I want to mock static method which is called within other static method.
public class MyClass
{
public static void methodA(String s)
{
...
methodB(s);
...
}
public static void methodB(String s)
{
...
}
}
So, I want to mock methodA, but I want to skip calling methodB.
I tried almost all solutions that I was able to find, without any success. Every time methodB is called.
Some solutions that I used:
PowerMockito.suppress(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.stub(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.mockStatic(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
And many others... Anyone have an idea how to solve this problem?
In my opinion you should Spy your class instead of mocking it.
In that situation all the static methods will be called with real implementation and on top of that you could instruct to not call methodB:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
class MyClassTest
{
@Test
public void test()
{
PowerMockito.spy(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
}
}
I have written an article on Mocking Static Methods if you need a further read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With