I think this is possible with PowerMock only if the method on the child is different from the method on the superclass (i.e., you cannot mock the parent method if the child overrides that method). For a little more detail, you can look at the relevant bug report.
For PowerMock, check out Suppressing Unwanted Behavior page to see if it will be enough for your needs.
After much digging around, I ended up using JMockit for these tricky cases. Before I moved on to JMockit, I tried stubbing out all the places exceptions were thrown using suppression. In the end, I needed to override some methods, and not just suppress them, so I ended up abandoning it.
Example usage for Android case:
First, you mock out 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 unit under test is derived from Activity (in my sample code, it is HelloTestActivity). The test class looks like this:
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)
{
// Try to access out-of-band information from the fake
activity.onCreate(savedInstanceState);
assertSame(savedInstanceState, fakeActivity.mSavedInstanceState);
}
}
The call Mockit.setupMock(fakeActivity) replaces the super class with my instance of the fake. With this usage, you can access internal state of your fake class as well. If you don't need to override any methods with custom functionality, you can use other methods available from Mockit class.
As rogerio pointed out in the comments below, mocking the Activity class is the bare minimum. The following code demonstrates this.
public class HelloTestActivityTest4 {
@Tested
HelloTestActivity activity;
@Mocked
Activity base;
@Test
public void testOnCreate() throws Exception {
// Just make sure "Stub!" exception is not thrown.
activity.onCreate(null);
}
}
The declaration @Mocked Activity base; causes all methods (excepting static initializers) of Activity class and its superclasses to be mocked in the tests defined in HelloActivityTest4.
super()from the mock, the mock is the superclass. Please see my edits. - Jeff AxelrodSvery much. - DerMike