閱讀890 返回首頁    go 阿裏雲 go 技術社區[雲棲]


分析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。

最後更新:2017-04-02 16:47:36

  上一篇:go 過了30歲,程序員該怎麼辦?
  下一篇:go 《iPhone與iPad開發實戰—iOS經典應用剖析》連載五