PowerMock: stub methods from parent class
Solution 1
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/
Solution 2
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));
Solution 3
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.
Related videos on Youtube
jchitel
Updated on June 13, 2022Comments
-
jchitel about 2 years
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()); }
-
Keith almost 9 yearsWhat's happening in the current test case?
-
jchitel almost 9 yearsIt's stubbing the subclass's method.
-
javaPlease42 about 8 yearsSeems like this bug :github.com/jayway/powermock/issues/487
-
-
jchitel over 8 yearsYea, 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!
-
javaPlease42 almost 8 yearsThe
suppress
method is not helpful because I need to return a mocked value. Thank you though. -
Steve almost 8 yearsHow about using PowerMockito.replace() to replace the parents method with one that returns your mocked value?