Android Test Framework performClick()无法启动Activity

时间:2012-12-13 08:09:57

标签: android android-testing

我有ActivityInstrumentationTestCase2测试执行Button.click()。 Button应该启动另一个Activity来做一些工作。 我认为Button.performClick()已正确执行,但测试在执行其他Activity之前完成。

@UiThreadTest
public void test() {

    Intent i = new Intent(this.myActivity, MyActivity.class);
    myActivity.startActivity(i);    


    Button button = (Button) myActivity.findViewById(R.id.button);
    button.performClick();


}

我尝试了下面的工作,但我认为这是一个解决方案,而不是一个好的解决方案。

public void test() {

    Intent i = new Intent(this.myActivity, MyActivity.class);
    myActivity.startActivity(i);    


    Button button = (Button) myActivity.findViewById(R.id.button);
    button.performClick();

    try {
    Thread.sleep(50000);
    } catch (InterruptedException e) {
        Log.e("MyTest", e.getMessage());
    }


}

有没有更好的方法?

1 个答案:

答案 0 :(得分:0)

这是我的最终解决方案:

public void test() {

    Instrumentation instrumentation = getInstrumentation();

    // Prepare a monitor for your activity
    Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(MyActivity.class.getName(), null, false);

    // Start your activity manually
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setClassName(instrumentation.getTargetContext(), MyActivity.class.getName());
    instrumentation.startActivitySync(intent);

    Activity myActivity = getInstrumentation().waitForMonitor(monitor);

    Button upSend = (Button) myActivity.findViewById(R.id.button);
    upSend.performClick();

    Log.d("MyTest", "button clicked");

    //wait for SecondActivity to start (called by MyActivity)
    monitor = instrumentation.addMonitor(SecondActivity.class.getName(), null, false);
    Activity secondActivity = getInstrumentation().waitForMonitor(monitor);

    int count = 0;

    //wait until SecondActivity is finishing
    while(!secondActivity.isFinishing()) {

        Log.d("MyTest", "waiting - " + ++count);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

            Log.e("MyTest",e.getMessage());
        }
    }

}
再次感谢Erik;现在第二个活动由按钮启动,测试正在等待它完成。