分析SpinnerActivityTest中有关控件操作以及UI线程问题

首先说明,SpinnerActivityTest是官方给的单元测试sample.


继承自ActivityInstrumentationTestCase2进行activity测试。涉及到对控件的操作时比如处理动作,触屏和按键事件,和锁屏。,必须在mActivity.runOnUiThread()程序线程中
(或者在测试函数上添加@UiThreadTest,那么整个函数将在UI线程中运行),而不是在测试线程中
比如:
mActivity.runOnUiThread(
            new Runnable() {
                public void run() {
                    mSpinner.requestFocus();
                    mSpinner.setSelection(INITIAL_POSITION);
                }
            }
        );
比如:
@UiThreadTest
    public void testStatePause() {


        Instrumentation instr = this.getInstrumentation();
        mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION);
        mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION);
	...
}

还有第三种方法,那就是直接通过Activity调用
比如:
mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
 mActivity.setSpinnerSelection(TEST_STATE_DESTROY_SELECTION);

为什么可以这样呢?
        /*
         * Set the position and value of the spinner in the Activity. The test runner's
         * instrumentation enables this by running the test app and the main app in the same
         * process.
         */
Also, instrumentation can load both a test package and the application under test into the same process. Since the application components and their tests are in the same process, the tests can invoke methods in the components, and modify and examine fields in the components.

可以看出Instrumentation和被测试的application是同进程的,Instrumentation可以让test app和被测试的app跑在同一个process.而getActivity()就是Instrumentation的方法,所以通过直接调用mActivity的setSpinner*方法,Instrumentation就会帮助你联通被测试的UI线程

注意:不与UI交互的方法不允许在UI线程中调用;例如,你不能触发Instrumentation.waitForIdleSync()或者sendkeys。

上一篇:WPF查找父元素子元素


下一篇:数据库维护