2

I have an Espresso test suite for UI tests that looks like this:

@RunWith(AndroidJUnit4.class)
public class SpecialUiTests {

    @Rule
    public final ActivityTestRule<SpecialActivity> activity 
                        = new ActivityTestRule<>(SpecialActivity.class);

    @Test
    public void specialTest() {
        ...
    }

    ...

}

The problem is, that activity expects a bundle, and crashes when it can't find the value it expects

public class SpecialActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

        final String specialValue = getIntent().getBundleExtra(ARG_SPECIAL_BUNDLE)
                        .getString(KEY_SPECIAL_VALUE);

        //Do something with specialValue <--- Crash

    }

    ...

}

Can I set up a test rule and still pass the parameter (a bundle) the activity expects?

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124

2 Answers2

5
@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(
SpecialActivity.class,
true,    // initialTouchMode
false);  //Lazy launching

@Test
public void specialTest() {
    Intent intent = new Intent();
    Bundle bundle = new Bundle();
    bundle.putString(SpecialActivity.KEY_SPECIAL_VALUE, "789");
    intent.putExtra(SpecialActivity.ARG_SPECIAL_BUNDLE, bundle);
    activityRule.launchActivity(intent);

  onView(withId(R.id.special))
      .check(matches(withText("789")));
}

Source: http://blog.sqisland.com/2015/04/espresso-21-activitytestrule.html

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
Geralt_Encore
  • 3,721
  • 2
  • 31
  • 46
1

You can also override getActivityIntent() of your ActivityTestRule to create the Intent. This way, an Activity with the appropriate Intent is started automatically for all of your test methods. Sample:

@Rule
public ActivityTestRule<SpecialActivity> mActivity = new ActivityTestRule<SpecialActivity>(SpecialActivity.class) {
    @Override
    protected Intent getActivityIntent() {
        final Context targetContext = InstrumentationRegistry.getTargetContext();
        final Intent intent = new Intent(targetContext, SpecialActivity.class);
        intent.putExtra("arg_one", 1);
        return intent;
    }
};
splatte
  • 2,048
  • 1
  • 15
  • 18