简体   繁体   中英

PowerMock not stubbing static method properly?

I'm trying to write a VERY simple test, using powermock and Robolectric. Here's my code:

import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.robolectric.RobolectricTestRunner;

import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(RobolectricTestRunner.class)
@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
@PrepareForTest(BadStaticClass.class)
public class SomeActivityTest {

    @Test
    public void testSomething() {
        PowerMockito.mockStatic(BadStaticClass.class);
        Mockito.when(BadStaticClass.dontWantThisMethod()).thenReturn(false);
        new SomeActivity().usesStatic();
    }
}

Basically, i have a class, "SomeActivity", and it has a method that makes a call to BadStaticClass.dontWantThisMethod() . i want that static method to be stubbed out.

why is my code not working?

i kept getting errors like: you are trying to stub a final method, you naughty developer!

which, i thought the whole point of PowerMock was to not see that.

According to the PowerMock API you have to include @RunWith(PowerMockRunner.class) for certain versions of JUnit, etc. However you also need to be using @RunWith(RobolectricTestRunner.class) and cannot specify more than one @RunWith on a Class.

So what to do?

I suspect you can keep your code above and introduce a JUnit @Rule (see: PowerMockRule docs ) and also described in this similar post . Just be sure you check the versions of the Jars you are using so that they match those described in that other SO post. All too often things just won't work unless you get compatible versions, and it's not always obvious what versions are compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM