Skip to content Skip to sidebar Skip to footer

Creating Intent In Test: "method Putextra In Android.content.intent Not Mocked"

I'm trying to unit test a broadcast receiver which listens for 'com.android.music.metachanged' intents using JUnit4 and Mockito. The broadcast receiver starts a service when it rec

Solution 1:

If you're like me and saw this error when running unit tests, but you didn't care about testing the putExtra portion of the code, you can use:

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

in your app's build.gradle file.

Solution 2:

All right, I took a look at Method of ContentValues is not mocked as suggested by @Jeff Bowman. Sadly, that question doesn't provide any code, so I hope this will be useful for somebody...

@RunWith(PowerMockRunner.class)
publicclassMusicBroadcastReceiverUnitTest {
    private MusicBroadcastReceiver mReceiver;

    @Mock
    private Context mContext;

    @Mock
    private Intent androidIntent;

    @Before
    publicvoidsetUp() {
        MockitoAnnotations.initMocks(this);

        mReceiver = new MusicBroadcastReceiver();
    }

    @Test
    publicvoidtestStartMusicRegistrationService() {
        try {
        PowerMockito.whenNew(Intent.class)
               .withArguments(String.class).thenReturn(androidIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        when(androidIntent.getAction())
          .thenReturn("com.android.music.metachanged");
        when(androidIntent.getStringExtra("artist"))
          .thenReturn("SampleArtist");

        mReceiver.onReceive(mContext, intent);

        ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
        verify(mContext, times(1)).startService(argument.capture());

        Intent receivedIntent = argument.getValue();
        assertEquals("SampleArtist", receivedIntent.getStringExtra("artist"));
    }
}

So yeah, I rather mocked "getStringExtra" than "putExtra". But it worked for me.

Post a Comment for "Creating Intent In Test: "method Putextra In Android.content.intent Not Mocked""