android - Activity 因缺少 Junit ActivityTestRule 参数而崩溃

标签 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() {
        ...
    }

    ...

}

问题是,该 Activity 需要一个包,并在找不到它期望的值时崩溃

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

    }

    ...

}

我可以设置一个测试规则并仍然传递 Activity 期望的参数(一个包)吗?

最佳答案

@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

关于android - Activity 因缺少 Junit ActivityTestRule 参数而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38845038/

相关文章:

android - 我在哪里可以找到 com.android.internal.R.styleable.AlertDialog_multiChoiceItemLayout 的来源?

scala - 未找到 Scala 特征中的 @Test 方法

testing - ScalaTest 和 Maven : getting started

android - onWebView 在层次结构中找不到匹配 : WebView with JS enabled 的 View

android - 同时进行 Espresso 自动和手动测试

java - Espresso : What are the advantages/disadvantages of having multiple tests vs. 一个用户旅程?

Android - 带复选框的 ListView

Android:如何调用其他 API 级别中存在的方法?

java - 将参数从测试套件发送到 junit 4 中的测试用例

android - 我应该扩展 ListActivity 吗? (到目前为止,没有它已经很好地工作了)