PowerMock无法初始化最终课程

时间:2017-05-10 22:58:07

标签: mockito powermock robolectric

我正在使用Robolectric 3.3.2和PowerMock对最终类进行单元测试。

@RunWith(RobolectricTestRunner.class)
@Config(sdk = 23)
@PrepareForTest({ FinalClass.class})
public class FragmentTest {

    private TestFragment mFragment;
    private TestActivity mActivity;

    private FinalClass mFinalClassMock;

    @Before
    public void setUp() throws Exception{

        mFinalClassMock = PowerMockito.mock(FinalClass.class);
        PowerMockito.whenNew(FinalClass.class).withAnyArguments()
                    .thenReturn(mFinalClassMock);
        mActivity = Robolectric.buildActivity(TestActivity.class)
                            .create().start().resume().get();
        mFragment = new TestFragment();

    }
}

失败,但有以下异常。

  

java.lang.IllegalArgumentException:无法继承最终类类com.android.contacts.common.preference.ContactsPreferences       在org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:447)       在org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)       在org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)       在org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)       在org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)       在org.powermock.api.mockito.repackaged.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)       在org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:57)       在org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)       在org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:59)       在org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:143)

我使用的是JUNIT 4.12和Powermock 1.6.4。 根据另一篇文章的建议更改了junit和powermock的版本,但没有成功。 最近有人遇到过这个问题吗?

1 个答案:

答案 0 :(得分:0)

在类中添加规则似乎可以解决问题

@Rule
public PowerMockRule rule = new PowerMockRule();