I think this is possible with PowerMock only if the child’s method is different from the method of the superclass (i.e. you cannot mock the parent method if the child overrides this method). For more information, you can see the corresponding error report .
For PowerMock, check out “Suppressing unwanted behavior page” to see if this is enough for your needs.
After much digging, I ended up using JMockit for these complex cases. Before I switched to JMockit, I tried to align all places except that exceptions were thrown. In the end, I needed to override some methods, not just suppress them, so I left it.
Usage example for Android case:
First, you mock your superclass using the @MockClass annotation:
@MockClass(realClass = Activity.class, instantiation = PerMockedInstance) public class FakeActivity { public Bundle mSavedInstanceState; @Mock public void $init() {} @Mock public void onCreate(Bundle savedInstanceState) { mSavedInstanceState = savedInstanceState; } }
When activated, this class will replace the default constructor of Activity with $init() and replace the onCreate method with the one above. WIth android, the test block is obtained from Activity (in my code example, this is HelloTestActivity ). The testing class is as follows:
public class HelloTestActivityTest3 extends AndroidTest { @Tested HelloTestActivity activity; FakeActivity fakeActivity = new FakeActivity(); @Before public void setupMocks() { Mockit.setUpMock(fakeActivity); } @Test public void onCreate_bundle(@Mocked Bundle savedInstanceState) {
Calling Mockit.setupMock(fakeActivity) replaces the superclass with my fake instance. With this use, you can also access the internal state of your fake class. If you do not need to override any methods using special functions, you can use other methods available from the Mockit class.
As Rogerio noted in the comments below, the mockery of the Activity class is minimal. The following code demonstrates this.
public class HelloTestActivityTest4 { @Tested HelloTestActivity activity; @Mocked Activity base; @Test public void testOnCreate() throws Exception {
@Mocked Activity base; declaration @Mocked Activity base; forces all methods (except static initializers) of the Activity class and its superclasses to be mocked in the tests defined in HelloActivityTest4 .