Mock android.os.BaseBundle without roboelectric

自古美人都是妖i 提交于 2020-06-17 04:34:35

问题


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;
}

This is the unit test :

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

However, it always returns:

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

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:


1) Add proper set-up

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

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

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

3) Use Powermock for whenNew():

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



回答2:


Try to add this in your build.gradle

android {
    testOptions {
        unitTests {
            unitTests.returnDefaultValues = true
        }
    }
}



回答3:


I finally get the answer from my friend. The reason is somehow for mocking android class using powermockito the main class need to be set as prepared for test too :

@PrepareForTest({MainClass.class, Bundle.class})

Thank you for the effort @Maciej Kowalski. I'll vote up for your effort since it's on the right direction anyway.

I'm not copy pasting the answer from above, preparing the test for MainClass is the important part.



来源:https://stackoverflow.com/questions/47830130/mock-android-os-basebundle-without-roboelectric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!