Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMock: how to suppress parent methods on a Spy?

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?

like image 573
Villa Avatar asked Mar 14 '23 06:03

Villa


1 Answers

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();
}
like image 192
Ruben Avatar answered Mar 24 '23 22:03

Ruben