模拟静态方法

Mil*_*rad 3 java unit-testing mocking mockito powermock

我想模拟在其他静态方法中调用的静态方法.

public class MyClass
{
    public static void methodA(String s)
    {
        ...
        methodB(s);
        ...
    }
    public static void methodB(String s)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我想嘲笑methodA,但我想跳过电话methodB.我尝试了几乎所有我能找到的解决方案,没有任何成功.每次都methodB被召唤.

我使用的一些解决方案:

PowerMockito.suppress(method(MyClass.class, "methodB"));
MyClass.methodA("s");
Run Code Online (Sandbox Code Playgroud)

_

PowerMockito.stub(method(MyClass.class, "methodB"));
MyClass.methodA("s");
Run Code Online (Sandbox Code Playgroud)

_

PowerMockito.mockStatic(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
Run Code Online (Sandbox Code Playgroud)

还有很多人......任何人都知道如何解决这个问题?

Mac*_*ski 5

在我看来,你应该窥探你的课而不是嘲笑它.

在这种情况下,所有静态方法都将通过实际实现调用,最重要的是你可以指示不调用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");
    }
}
Run Code Online (Sandbox Code Playgroud)