PowerMock:如何在Spy上抑制父方法?

Vil*_*lla 3 java mockito powermock powermockito

如何在Spy上正确抑制父类方法?

如果我有一个班级家长:

public class Parent {
    public void method() {
    System.out.println("Parent.method");
    }
}

class Child extends Parent {
@Override
    public void method() {
        super.method();
        System.out.println("Child.method");
    }
}
Run Code Online (Sandbox Code Playgroud)

我用以下代码测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Parent.class)
public class SuppressParentTest {
   @Spy Child child = new Child();

   @Test
   public void testSuppressSuperclassMethods() {
       PowerMockito.suppress(methodsDeclaredIn(Parent.class));
       child.method();
   }
Run Code Online (Sandbox Code Playgroud)

我从System.out获得以下打印输出:

Parent.method
Child.method
Run Code Online (Sandbox Code Playgroud)

而我应该只打印一份Child.method.

有趣的是,如果我@Spy从Child对象的声明中删除注释,则会Parent.method()被正确抑制.

难道我做错了什么?我是否误解了如何使用PowerMock?

Rub*_*ben 6

问题是订购.

在你的测试中,Powermock首先创建了Child Spy,然后你要求他压制方法Parent.这一点似乎已经太晚了,因为Child实例已经创建了.

如果您先调用suppress然后创建它Child,它的工作原理如下:

@Test
public void testSuppressSuperclassMethods() {
    PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(Parent.class));
    Child child = spy(Child.class);
    child.method();
}
Run Code Online (Sandbox Code Playgroud)