24

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());
}
jchitel
  • 2,999
  • 4
  • 36
  • 49

3 Answers3

6

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/

Steve
  • 981
  • 1
  • 8
  • 22
3

Don't forget to add @PrepareForTest({ParentClassToSupress.class}) on your test class. Then you can do as Steve suggests and suppress methods in the parent: PowerMockito.suppress(methodsDeclaredIn(ParentClassToSupress.class));

DustinB
  • 11,037
  • 5
  • 46
  • 54
1

The cast you're attempting is not going to work as you are expecting. However, I think you have a couple of options to get around this, certainly with PowerMockito.

Take a look at this StackOverflow answer.

Community
  • 1
  • 1
Keith
  • 3,079
  • 2
  • 17
  • 26
  • 1
    Yea, so I was trying really hard to find a solution to this because the point of PowerMock is that you shouldn't have to change the structure of your code to make it testable. However, I realized that I need to balance that with the amount of time and effort it takes me to write the tests, so I modified the code to make it easier to test. But thanks for the resource! – jchitel Sep 27 '15 at 07:42