I found this example where they used PowerMock and EasyMock to stub/mock the Menu and MenuItem classes for android. I have been trying to do something similar with PowerMock and Mockito with the Activity class.
I understand that a lot of the methods are final and that in the Android.jar they all just throw RuntimeException("Stub!").
I also understand that this test isn't complete but I just wanting to see if it is possible to mock the android Activity class.
But given that PowerMock allows you to mock classes with final methods shouldn't this code work?
@RunWith(PowerMockRunner.class)
@PrepareForTest(Activity.class)
public class MyTestCase extends TestCase {
public void testPlease_JustWork() throws Exception {
Ac开发者_运维百科tivity mockActivity = PowerMockito.mock(Activity.class);
PowerMockito.when(mockActivity.getTitle()).thenReturn("Title");
}
}
I would think that the RuntimeException would no longer occur and "Title" would be returned but it still throws the exception.
I have tried all sorts of different things like doReturn("Title").when(mockActivity).getTitle();
and suppress(constructor(Activity.class));
Am I doing something wrong or is this just not possible?
Probably not a direct answer to your question, but you could try Robolectric in order to test parts of your Android app on your PC.
Roboelectric avoids the Stub! exception and gives you some minimal Android classes implementation
I think the answer is that the order of your referenced libraries matters because the android.jar includes some stubs for junit.
You have to ensure that on your test project, if you go to 'properties' and then 'Java Build Path' that the junit jar associated with the full version of powermock you downloaded show up on the 'Order and Export' tab above the android.jar. If it does not, the system resolves the junit.framework and junit.runner packages from android.jar before it resolves them from the junit.jar included in powermock.
I realize this question is old, but I think this is the proper answer so i wanted to make sure to document it on the question.
I just tried your code sample and it works here, strange. I downloaded PowerMock 1.4.5 with Mockito and JUnit including dependencies and used the android.jar from the sdk (2.2). It only fails with the exception if i remove the @PrepareForTest.
EDIT
You could use the android.jar with the removed exception code, provided in the article you referenced.
精彩评论