2

我有一个用于 UI 测试的 Espresso 测试套件,如下所示:

@RunWith(AndroidJUnit4.class)
public class SpecialUiTests {

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

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

    ...

}

问题是,该活动需要一个捆绑包,并且在找不到它期望的值时崩溃

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

    }

    ...

}

我可以设置测试规则并仍然传递活动期望的参数(捆绑包)吗?

4

2 回答 2

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

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

于 2016-08-09T08:11:56.757 回答
1

您还可以覆盖getActivityIntent()ActivityTestRule的创建意图。这样,具有适当 Intent 的 Activity 会为您的所有测试方法自动启动。样本:

@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;
    }
};
于 2016-08-11T07:52:00.613 回答