gpt4 book ai didi

Android Instrumentation 启动 Activity

转载 作者:太空狗 更新时间:2023-10-29 13:30:59 25 4
gpt4 key购买 nike

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

最佳答案

假设您有一个扩展 InstrumentationTestCase 的测试类,并且您在一个测试方法中,它应该遵循以下逻辑:

  1. 注册您对要检查的 Activity 感兴趣。
  2. 启动它
  3. 用它做你想做的事。检查组件是否正确、执行用户操作等等。
  4. 登记您对“序列”中的下一个 Activity 的兴趣
  5. 执行该 Activity 的操作,使序列中的下一个 Activity 弹出。
  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.");

关于Android Instrumentation 启动 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15460949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com