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