Mocking static method

I want to mock a static method that is called inside another static method.

public class MyClass
{
    public static void methodA(String s)
    {
        ...
        methodB(s);
        ...
    }
    public static void methodB(String s)
    {
        ...
    }
}

      

So, I want to make fun of methodA

, but I want to miss the challenge methodB

. I have tried almost every solution I could find without any success. Called every time methodB

.

Some solutions I've 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 more ... Anyone have an idea how to solve this problem?

+3


source to share


1 answer


In my opinion, you should spy on your class, not mock it.

In this situation, all static methods will be called with the real implementation, and in addition, you could instruct not to 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 wrote an article on Mocking Static Methods if you need to read more.

+5


source







All Articles