Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempt to stub android Activity class using PowerMockito throws RuntimeException "Stub!"

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 {
        Activity 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?

like image 525
bytebender Avatar asked Sep 17 '10 23:09

bytebender


2 Answers

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

like image 79
superjos Avatar answered Oct 19 '22 11:10

superjos


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.

like image 45
Nick Campion Avatar answered Oct 19 '22 11:10

Nick Campion