本文介绍了Robolectric和Powermock之间的类加载冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写同时需要 Robolectric 2.2和 PowerMock 的测试,因为受测试的代码取决于某些Android库和具有最终类的第三方库

I'm trying to write a test that needs both Robolectric 2.2 and PowerMock, as the code under test depends on some Android libraries and third party libraries with final classes that I need to mock.

鉴于我被迫通过以下方式使用Robolectric测试运行器:

Given that I'm forced to use the Robolectric test runner through:

@RunWith(RobolectricTestRunner.class)

...我不能使用PowerMock测试运行程序,所以我试图使用PowerMock Java代理替代方案,到目前为止还没有运气。

...I cannot use the PowerMock test runner, so I'm trying to go with the PowerMock java agent alternative, without luck so far.

我已经根据,但是我正面临javaagent库和robolectric所需的类之间的冲突问题,因为它们与asm- 1.4。两者都取决于

I have setup everything according to this guide but I'm facing a collision problem between classes required by the javaagent library and by robolectric through its dependency with asm-1.4. Both depend on

,但是javaagent-1.5.1附带了自己的版本,其中ClassVisitor是接口,而同一名称空间的asm-1.4版本是抽象类,在运行时具有相应的错误:

, but javaagent-1.5.1 ships with its own version where ClassVisitor is an interface while asm-1.4 version for the same namespace is an abstract class, with the corresponding error at runtime:

java.lang.IncompatibleClassChangeError: class org.objectweb.asm.tree.ClassNode has interface org.objectweb.asm.ClassVisitor as super class

我什至尝试修改javaagent库jar来完全删除其中的org.objectew.asm类,但这并没有由于org.objectweb.asm包中需要一些其他类,这些类仅在javaagent库jar中提供,而在asm中不提供,因此之后发生ClassNotFoundException便无法正常工作。

I have even tried to modify the javaagent library jar to entirely remove the org.objectew.asm classes in there, but that doesn't work as ClassNotFoundException happens afterwards due to some other classes needed in the org.objectweb.asm package that only ship in the javaagent library jar, and not in the asm one.

有什么想法吗?根据那里的示例,该代理似乎至少可以与Spring测试运行器一起正常工作。

Any ideas? According to examples out there the agent seems to work fine with, at least, the Spring test runner.

推荐答案

问题,虽然我没有解决这个问题,但我想分享我的方法,从而消除了对PowerMock的需求(在我看来,这始终是一件好事):我想模拟对

I had the same problem and while I didn't solve this problem as such, I wanted to share my approach, which removes the need for PowerMock (which is always a good thing in my view): I wanted to mock a call to

Fragment fooFragment = new FooFragment();

所以我要做的是另外一个间接级别。我创建了一个FragmentProvider类:

So what I did was addanother level of indirection. I created a FragmentProvider class:

public FragmentFactory fragmentFactory = new FragmentFactory();
[...]
Fragment fooFragment = fragmentFactory.getFooFragment();

完成此操作后,我可以使用标准Mockito模拟工厂,如下所示:

After i did this, I could just mock out the factory with standard Mockito, like this:

FragmentFactory mockFactory = mock(FragmentFactory.class);
activity.fragmentFactory = mockFactory;
when(mockFactory.getFooFragment()).thenReturn(mockFooFragment);

这篇关于Robolectric和Powermock之间的类加载冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 12:38