Junit ActivityTestRule中缺少参数的活动崩溃

时间:2016-08-09 07:51:19

标签: android junit4 android-espresso uitest

我有一个用于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

    }

    ...

}

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您还可以覆盖getActivityIntent()的{​​{1}}来创建意图。这样,将为所有测试方法自动启动具有相应Intent的Activity。样品:

ActivityTestRule