Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock android.os.BaseBundle without roboelectric

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.

like image 225
surga Avatar asked Oct 28 '25 05:10

surga


2 Answers

Try to add this in your build.gradle

android {
    testOptions {
        unitTests {
            unitTests.returnDefaultValues = true
        }
    }
}
like image 51
Levon Petrosyan Avatar answered Oct 30 '25 23:10

Levon Petrosyan


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);
like image 44
Maciej Kowalski Avatar answered Oct 30 '25 23:10

Maciej Kowalski