Skip to content Skip to sidebar Skip to footer

Using Powermock And Robolectric - Incompatibleclasschangeerror

I'm trying to use PowerMockito to mock some static methods in Android Robolectric tests. I'm using JUnit 4.8.2, Robolectric 2.2, Mockito 1.9.5, and PowerMock 1.9.5 as directed her

Solution 1:

I found a way to use PowerMock in conjunction with Robolectric.

In addition to the standard PowerMock jars, the PowerMock Junit Rule is also needed. It is described here how to grab it. I used the xstream classloading version, because the objenesis one is very buggy. This is working with PowerMock 1.5.5 and Robolectric 2.3, i cannot speak about the older versions. Also please note that the Java agent should not be included, because from my experience it causes problems.

So if you are using maven, these dependencies should be declared:

<dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4-rule</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-api-mockito</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-classloading-xstream</artifactId><version>${powermock.version}</version><scope>test</scope></dependency>

Then you have to setup your test class like this:

@RunWith(RobolectricTestRunner.class)
@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
@PrepareForTest(Static.class)
publicclassMyTest {

    @Rule
    public PowerMockRule rule = new PowerMockRule();

    private MyActivity activity;

    @Before
    publicvoidsetup() {
        activity = Robolectric.buildActivity(MyActivity.class).create().get();
    }

    @Test
    publicvoidtest() throws Exception {
        PowerMockito.mockStatic(Static.class);
        Mockito.when(Static.getCurrentTime()).thenReturn(1);

        Assert.assertEquals(1, activity.getId());
    }
}

Post a Comment for "Using Powermock And Robolectric - Incompatibleclasschangeerror"