我有一个包含按钮的简单活动。当我按下按钮时,第二个活动运行。现在我对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应用程序的上下文中理解了这个异常,但现在是在仪器测试方面。如何执行按钮上的单击事件,以及如何检查是否已加载第二个活动。

最佳答案

假设您有一个扩展InstrumentationTestCase的测试类,并且您在一个测试方法中,那么它应该遵循以下逻辑:
注册您对要检查的活动的兴趣。
发射它
随你的便吧。检查组件是否正确,执行用户操作,诸如此类。
为“序列”中的下一个活动注册您的兴趣
执行该活动的操作,从而弹出序列的下一个活动。
重复,按照这个逻辑…
在代码方面,这将导致如下结果:

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

10-08 07:12