views:

124

answers:

2

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?

A: 

Try android-mock a port of easy mock to android code.google.com/p/android-mock/

Fred Grott
Still throws and exception "Stub!" It still appears to have to do with stubbing a final method that has been coded to just throw a RuntimeException no matter what...
J.13.L
A: 

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.

crazymaik
I will give it a try...
J.13.L
No dice, can you show me what your import lines look like?
J.13.L
i've uploaded the whole eclipse project to http://maik.0x2a.at/PowerMockTests.zip . You may need to adapt the path to the android.jar
crazymaik
Well... I was using the separate junit library that I had downloaded so once I just got the whole package from power mock that included everything and got rid of the refrences to the other junit library, created a new test class I got a green bar. So Thanks!
J.13.L
I also had some problems in case anyone else is trying this. I noticed that the order of the Java build path is important. If you go to the order and export tab in Eclipse, make sure your src folder is at the top, then JavaSE-1.6, then the PowerMock jars, then finally android.jar.
glenviewjeff