Android开发之Instrumentation(自动化测试)

Android在JUnit的之外给我们又提供了Instrumentation测试框架。通过Instrumentation可以模拟按键按下、抬起、屏幕点击、滚动等事件,有效地控制Activity进行自动化测试。

Instrumentation是执行application instrumentation代码的基类。当应用程序运行的时候instrumentation处于开启,Instrumentation将在任何应用程序运行前初始化,可以通过它监测系统与应用程序之间的交互。

imageimage

1. Manifest.xml中描述:

<instrumentation

android:name="android.test.InstrumentationTestRunner"

android:label="Tests for My App"

android:targetPackage="com.my.test" />

<span style="font-size:18px;"><uses-permission android:name="android.permission.INJECT_EVENTS" /></span>

2.模拟发送按键:

/**

     * 传入需要的键值即可

     * @param keyCode

     */

private void sendKeyCode(final int keyCode){ 

new Thread () { 

public void run() { 

try { 

                    Instrumentation inst = new Instrumentation(); 

                    inst.sendKeyDownUpSync(keyCode); 

                } catch (Exception e) { 

                    Log.e("Exception when sendPointerSync", e.toString()); 

                } 

            } 

        }.start(); 

    } 

}

3.模拟鼠标事件:

new Thread () { 

public void run () { 

try { 

                             Instrumentation inst=new Instrumentation(); 

                                     inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), 

                                     SystemClock.uptimeMillis(),  

                                     MotionEvent.ACTION_DOWN, 240, 400, 0)); 

                           inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), 

                                     SystemClock.uptimeMillis(),  

                                     MotionEvent.ACTION_UP, 240, 400, 0));   

                        } catch(Exception e) { 

                            Log.e("Exception when sendPointerSync", e.toString()); 

                        } 

                    } 

         }.start(); 

原文地址:https://www.cnblogs.com/waleyx/p/3650268.html