【问题标题】:Mocking static methods with Robolectric and PowerMockito使用 Robolectric 和 PowerMockito 模拟静态方法
【发布时间】:2017-03-07 04:22:16
【问题描述】:

我正在使用 Roboelectric 实现测试,并且我正在尝试实现一个必须检查静态方法是否已被调用的测试。我的测试是这样的:

@RunWith(RobolectricTestRunner.class)
@Config(manifest=Config.NONE)
@PrepareForTest({DeviceUtils.class})
@SmallTest
public class ContactsListPresenterTest extends BasePresenterTest {    
    ...

    @Test
    public void onCallContactClicked_nullArgument_methodNotCalled() {
        PowerMockito.mockStatic(DeviceUtils.class);
        presenter.onCallNotaryClicked(context, null);
        PowerMockito.verifyStatic(Mockito.never());
        DeviceUtils.dialPhoneNumber(context, Mockito.anyString());
    }
    @Test
    public void onCallContactClicked_nullArgument_methodCalled() {
        PowerMockito.mockStatic(DeviceUtils.class);
        presenter.onCallNotaryClicked(context, new Contact());
        PowerMockito.verifyStatic(Mockito.times(1));
        DeviceUtils.dialPhoneNumber(context, Mockito.anyString());
    }
}

但是测试失败并出现以下错误:

org.powermock.api.mockito.ClassNotPreparedException: 
The class x.DeviceUtils not prepared for test.
To prepare this class, add class to the '@PrepareForTest' annotation.
In case if you don't use this annotation, add the annotation on class or  method level. 

我做错了什么?我已经添加了@PrepareForTest 注释,我想这都是因为我使用的是 RobolectricTestRunner 而不是 PowerMockitoRunner,但是我需要 RoboelectricTestRunner 来进行同一类中的其他测试。

非常感谢

【问题讨论】:

    标签: android mockito robolectric powermock android-testing


    【解决方案1】:

    您使用的是PowerMockRule 吗?如 Robolectric 文档中所述

    【讨论】:

    • 如果我添加@Rule public PowerMockRule rule = new PowerMockRule();然后类中的所有测试都失败了: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.powermock.classloading.DeepCloner
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多