没有机器人的模拟 android.os.BaseBundle [英] Mock android.os.BaseBundle without roboelectric

查看:98
本文介绍了没有机器人的模拟 android.os.BaseBundle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对此代码进行单元测试:

I am trying to do a unit test on this code :

Bundle cidParam(String accountId) {
    Bundle params = new Bundle(1);
    params.putString(Params.CID, accountId);

    return params;
}

这是单元测试:

private void mockBundle(String cid) throws Exception {
    Bundle mBundle = PowerMockito.mock(Bundle.class);
    PowerMockito.doNothing().when((BaseBundle)mBundle).putString(AnalyticsController.Params.CID, cid);
}

但是,它总是返回:

java.lang.RuntimeException: Method putString in android.os.BaseBundle not mocked.

我知道我可以使用 roboelectric 来启动模拟器并调用真正的包.但是,它会减慢单元测试的速度.有谁知道如何模拟 Android .os.base?谢谢.

I know I can use roboelectric to spin up the simulator and call the real bundle. However, it will slow down the unit test. Does anyone know how to mock the Android .os.base? Thank you.

推荐答案

1) 添加适当的设置

@RunWith(PowerMockRunner.class)
@PrepareForTest(Bundle.class)
public class MyTest{

2)do().when() 使用 vanilla Mockito:

2) Use vanilla Mockito for do().when():

Bundle mBundle = PowerMockito.mock(Bundle.class);
    Mockito.doNothing().when(mBundle).putString(AnalyticsController.Params.CID, cid);

3)whenNew() 使用 Powermock:

3) Use Powermock for whenNew():

PowerMockito.whenNew(Bundle.class)
            .withAnyArguments().thenReturn(mBundle);

这篇关于没有机器人的模拟 android.os.BaseBundle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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