使用 PowerMock 和 Robolectric - 不兼容的类更改错误
我试图使用PowerMockito来模拟Android Robolectric测试中的一些静态方法。我正在使用JUnit 4.8.2,Robolectric 2.2,Mockito 1.9.5和PowerMock 1.9.5,如这里所示。由于我必须使用RoboElectricTestRunner,我正在尝试使用PowerMockRule来引导PowerMock。然而,当PowerMock的测试运行时,我遇到了一个不幸的问题。java.lang.IncompatibleClassChangeError
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:323) at sun.instrument.InstrumentationImpl.loadClassAndCallAgentmain(InstrumentationImpl.java:348)Caused by: java.lang.incompatibleClassChangeError: Implementing class at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637) at java.lang.ClassLoader.defineClass(ClassLoader.java:621) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
如果我把放在库之后,我得到:org.ow2.asm
org.powermock
java.lang.IncompatibleClassChangeError: class org.objectweb.asm.tree.ClassNode has interface org.objectweb.asm.ClassVisitor as super class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637) at java.lang.ClassLoader.defineClass(ClassLoader.java:621) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) atjava.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method)
在每个单元测试中。
根据Maven depency的说法:tree Robolectric和PowerMock不共享任何依赖项。但显然 org.powermock:powermock-module-javaagent 打包了一些 org/objectweb/asm 类,而 Robolectric 依赖于 org.ow2.asm:asm:jar:4.1 导致冲突。
@RunWith(RobolectricTestRunner.class)
@PrepareForTest(Helper.class)
@PowerMockIgnore({"com.sun.jmx.*", "javax.management.*"})
public class HelpFragTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
static {
PowerMockAgent.initializeIfNeeded();
}
FragmentActivity fragmentActivity;
FragmentManager fragmentManager;
ActionBarManager actionBarManager;
@Before
public void setup(){
actionBarManager = mock(ActionBarManager.class);
LowesApplication.instance().setActionBarManager(actionBarManager);
fragmentActivity = Robolectric.buildActivity(FragmentActivity.class).create().start().resume().get();
fragmentManager = fragmentActivity.getSupportFragmentManager();
}
@Test
public void testShow(){
mockStatic(Helper.class);
HelpFrag helpFrag = HelpFrag.newInstance();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(helpFrag, null);
fragmentTransaction.commit();
assertTrue(helpFrag.isVisible());
}
}