分析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
上一篇:
過了30歲,程序員該怎麼辦?
下一篇:
《iPhone與iPad開發實戰—iOS經典應用剖析》連載五
Android係列教程之七:EditText使用詳解-包含很多教程上看不到的功能演示
Why Apache Beam? A data Artisans perspective
清華大學馬少平教授:那些年,我們做過的AI……
C# 係統應用之獲取Windows最近使用記錄
Java中網絡編程之TCP協議
C# 根據列名與列值設置當前行
Java常用類庫--StringBuffer:append、insert、reverse、replace、subString、delete、indexOf
Git下使用Beyond Compare作為比較和合並工具
算法訓練-線段樹
如何才能成為一名優秀的軟件測試人員