Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking static method

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?

like image 937
Milorad Avatar asked Apr 09 '26 03:04

Milorad


1 Answers

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.

like image 171
Maciej Kowalski Avatar answered Apr 10 '26 15:04

Maciej Kowalski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!