Can I use Robolectric to test that an Activity starts a Service with a specific Bundle passed with the Intent?
I want to write a Robolectric-based test that tests that my MainActivity
starts MyService
with a specific number passed in intent extras:
in "MainActivity.java" I have the method
public void startMyService() {
Intent i = new Intent(this, MyService.class);
Bundle intentExtras = new Bundle();
intentExtras.putLong(MyService.INTENT_ARGUMENT_MAGIC_NUMBER, 3); // Three is the magic number
i.putExtras(intentExtras);
startService(i);
}
and this is my test case "MainActivityTest.java":
import ...
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTest extends TestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testShallPassMagicNumberToMyService() {
MainActivity activityUnderTest = Robolectric.setupActivity(MainActivity.class);
activityUnderTest.startMyService();
Intent receivedIntent = shadowOf(activityUnderTest).getNextStartedService();
assertNotNull("No intents received by test case!", receivedIntent);
Bundle intentExtras = receivedIntent.getExtras();
assertNotNull("No intent extras!", intentExtras);
long receivedMagicNumber = intentExtras.
getLong(MyService.INTENT_ARGUMENT_MAGIC_NUMBER);
assertFalse("Magic number is not included with the intent extras!",
(receivedMagicNumber == 0L)); // Zero is default if no 'long' was put in the extras
}
}
So, my question is: Can I use Robolectric for this purpose?
The test case does not work because it reports "No intent extras!". Using the debugger I've noticed that Intent.putExtras() has no effect in the Robolectric environment. The i.mExtras
(Intent.mExtras
) property is correctly set to a Bundle reference when I run the app on my device. When I run the test case it is null
. I suppose that this hints that the answer to my question is "no", so should I give up on this test case or is there any way to accomplish this test?
Aucun commentaire:
Enregistrer un commentaire