The android-test-support library has ditched the ActivityInstrumentationTestCase2 base class for a cleaner approach using JUnit4 rules. This is nice and clean, but te documentation is currently lacking on how to proceed if your Activity requires Intent extras to run. This post demonstrates how to make that work.

Heres the simplest case, where all activities are launched with the "android.intent.action.MAIN" action:

[sourcecode language=”java” collapse=”false”]
@SmallTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);

@Test
public void someTest() {
/* Your activity is initialized and ready to go. */
}
}
[/sourcecode]

Here’s how to make all methods in your test class use the same intent, with extras:

[sourcecode language=”java” collapse=”false”]
@SmallTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<MainActivity>(MainActivity.class) {
@Override
protected Intent getActivityIntent() {
Context targetContext = InstrumentationRegistry.getInstrumentation()
.getTargetContext();
Intent result = new Intent(targetContext, MainActivity.class);
result.putExtra("Name", "Value");
return result;
}
};

@Test
public void someTest() {
/* Your activity is initialized and ready to go. */
}
}
[/sourcecode]

If you want each test method to provide its own set of extras, you can do that too:

[sourcecode language=”java” collapse=”false”]
@SmallTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class, true, false);

@Test
public void someTest() {
Context targetContext = InstrumentationRegistry.getInstrumentation()
.getTargetContext();
Intent intent = new Intent(targetContext, MainActivity.class);
intent.putExtra("Name", "Value");

mActivityRule.launchActivity(intent);

/* Your activity is initialized and ready to go. */
}
}
[/sourcecode]

I have put a complete, running example on GitHub at barend/android-espresso-intent-sample.