安卓测试驱动程序启动活动

6

我有一个简单的活动包含一个按钮。当我按下按钮时,第二个活动运行。现在我对Android检测测试还不熟悉。到目前为止,这是我写的:

public class TestSplashActivity extends
    ActivityInstrumentationTestCase2<ActivitySplashScreen> {

private Button mLeftButton;
private ActivitySplashScreen activitySplashScreen;
private ActivityMonitor childMonitor = null;
public TestSplashActivity() {
    super(ActivitySplashScreen.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();
    final ActivitySplashScreen a = getActivity();
    assertNotNull(a);
    activitySplashScreen=a;
    mLeftButton=(Button) a.findViewById(R.id.btn1);

}

@SmallTest
public void testNameOfButton(){
    assertEquals("Press Me", mLeftButton.getText().toString());
    this.childMonitor = new ActivityMonitor(SecondActivity.class.getName(), null, true);
    this.getInstrumentation().addMonitor(childMonitor);
    activitySplashScreen.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            mLeftButton.performClick();
    }});

    Activity childActivity=this.getInstrumentation().waitForMonitorWithTimeout(childMonitor, 5000);
    assertEquals(childActivity, SecondActivity.class);

}

现在我获取按钮文本的第一个断言是有效的。但是当我调用perform click时,会出现异常。

  Only the original thread that created a view hierarchy can touch its views. 

我现在理解了Android应用程序中的这个异常,但是现在想在仪器测试的术语中理解它。我如何执行按钮的点击事件,以及如何检查我的第二个活动是否已加载。

1个回答

4
假设你有一个继承InstrumentationTestCase的测试类,并且你在一个测试方法中,它应该遵循以下逻辑:
  1. 注册您对要检查的活动的兴趣。
  2. 启动它
  3. 进行您想要的操作。检查组件是否正确,执行用户操作等。
  4. 为“序列”中的下一个活动注册您的兴趣
  5. 执行使序列的下一个活动弹出的那个活动的操作。
  6. 重复,按照这个逻辑...
就代码而言,这将导致以下内容:
Instrumentation mInstrumentation = getInstrumentation();
// We register our interest in the activity
Instrumentation.ActivityMonitor monitor = mInstrumentation.addMonitor(YourClass.class.getName(), null, false);
// We launch it
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(mInstrumentation.getTargetContext(), YourClass.class.getName());
mInstrumentation.startActivitySync(intent);

Activity currentActivity = getInstrumentation().waitForMonitor(monitor);
assertNotNull(currentActivity);
// We register our interest in the next activity from the sequence in this use case
mInstrumentation.removeMonitor(monitor);
monitor = mInstrumentation.addMonitor(YourNextClass.class.getName(), null, false);

如果要发送点击事件,请按照以下方式进行操作:

View v = currentActivity.findViewById(....R.id...);
assertNotNull(v);
TouchUtils.clickView(this, v);
mInstrumentation.sendStringSync("Some text to send into that view, if it would be a text view for example. If it would be a button it would already have been clicked by now.");

在我的应用程序中,点击按钮会启动新的活动。我想测试这种情况:当我点击按钮后,是否会启动第二个活动?我该如何测试这种情况? - user1730789
我明白了。不要像那样发送点击。你应该使用仪器类来发送点击。我已经编辑了我的帖子。 - Luis Miguel Serrano
1
为了跟上最新的技术,TouchUtils 类已经被弃用,现在应该使用 Espresso UI 测试。 - Ibrahim.H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接