How do I correctly suppress a parent class method on a Spy?
If I have a class Parent:
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");
}
}
that I test with the following code:
@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();
}
I get the following printout from System.out:
Parent.method
Child.method
whereas I should only get a printout of Child.method
.
Interestingly if I delete the @Spy
annotation from the declaration of the Child object, then Parent.method()
is correctly suppressed.
Am I doing something wrong? Do I misunderstand how to use PowerMock?
The problem is the ordering.
In your test, Powermock is first creating the Child
Spy
, and afterwards you ask him to supress the methods of Parent
. It seems that it is too late at that point, as the Child
instance has already been created.
If you first call the suppress
and then create the Child
, it works:
@Test
public void testSuppressSuperclassMethods() {
PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(Parent.class));
Child child = spy(Child.class);
child.method();
}
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