无法使用PowerMockito.spy()模拟/监视最终类 [英] Cannot mock/spy final class using PowerMockito.spy()

查看:1057
本文介绍了无法使用PowerMockito.spy()模拟/监视最终类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PowerMockito创建一个 final 类的间谍,但是即使使用PowerMockito的 spy()方法代替Mockito的方法:

I'm trying to use PowerMockito to create a spy of a final class but I keep getting the following error, even though I am using PowerMockito's spy() method in place of Mockito's:


java.lang.IllegalArgumentException:无法对最终类进行继承com.whoever.WidgetUploadClient

java.lang.IllegalArgumentException: Cannot subclass final class class com.whoever.WidgetUploadClient

我的测试用例看起来像这样:

My test case looks something like this:

...
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.spy;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(RobolectricTestRunner.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@PrepareForTest(WidgetUploadClient.class)
@Config(manifest=Config.NONE, sdk = 23)
public class WidgetUploadClientTest {
    @Test
    public void testUploadWidget() {
        WidgetMarshaller mockMarshaller = mock(WidgetMarshaller.class);
        WidgetUploadClient client = spy(new WidgetUploadClient(mockMarshaller)); // Exception thrown by spy()
        ...
    }
}


$ b $抛出的异常b

不要 @PrepareForTest(WidgetUploadClient.class),并使用PowerMockito的 spy()方法帐户 WidgetUploadClient 是最终版本吗?

Shouldn't @PrepareForTest(WidgetUploadClient.class) and using PowerMockito's spy() method account for WidgetUploadClient being final?

我还尝试了Robolectric的 PowerMock指南:使用 RobolectricTestRunner RobolectricGradleTestRunner 作为测试运行程序( @RunWith )与 @Rule公共PowerMockRule规则= new PowerMockRule()。当我这样做时,测试将无法完全运行,并引发另一个异常。

I have also tried the alternative approach found in Robolectric's PowerMock guide: using RobolectricTestRunner or RobolectricGradleTestRunner as the test runner (@RunWith) with @Rule public PowerMockRule rule = new PowerMockRule(). When I do that, the test fails to run entirely and a different exception is thrown.

我正在使用PowerMock / PowerMockito 1.6.5,Robolectric 3.1和Java 1.8.0_91 -b14。

I am using PowerMock/PowerMockito 1.6.5, Robolectric 3.1 and Java 1.8.0_91-b14.

推荐答案

我相信我正确使用了API,但是遇到了一个影响开发人员尝试使用API​​的错误。 Robolectric和PowerMock的组合。作为参考,可以在Robolectric的问题跟踪器上跟踪该错误。至少自2016年1月(目前约6个月前)以来,图书馆的组合已被破坏。

I believe that I am using the APIs correctly but am experiencing by a bug that effects developers trying to use the combination of Robolectric and PowerMock. For reference, the bug can be tracked on Robolectric's issue tracker. The combination of libraries has been broken since at least January 2016 (currently ~6 months ago.)

这篇关于无法使用PowerMockito.spy()模拟/监视最终类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆