PowerMock: stub methods from parent class

jchitel picture jchitel · Sep 23, 2015 · Viewed 14.9k times · Source

I'm using PowerMock and I'd like to know how to keep all behavior of the child class, but stub super calls that may be overriden by the child.

Say I have this class:

public class A {
    public String someMethod() {
        return "I don't want to see this value";
    }
}

and a sub class:

public class B extends A {
    @Override
    public String someMethod() {
        return super.someMethod() + ", but I want to see this one";
    }
}

How do I stub the call to super.someMethod()?

I've tried

@Test
public void test() {
    B spy = PowerMockito.spy(new B());
    PowerMockito.doReturn("value").when((A)spy).someMethod();

    assertEquals("value, but I want to see this one", spi.someMethod());
}

Answer

Steve picture Steve · Jul 8, 2016

You can try suppressing the methods from the Parent class,

PowerMockito.suppress(methodsDeclaredIn(A.class));

Here's an article on Stubbing, suppressing and replacing with PowerMock that might be of some use.

https://www.jayway.com/2013/03/05/beyond-mocking-with-powermock/