Instrumentation

Instrumentation直接的说是安卓源码里的一个类,在启动app的时候都会实例化一个Instrumentation对象,主要有2个作用:

  • 在activity跳转的时候,其内部类ActivityMonitor会监控activity的加载
  • activity的生命周期的触发也是通过它来调用的

对应用开发人员,Instrumentation的作用更多的是在自动化测试上。

自动化测试

自动化测试不是直接使用Instrumentation,而是使用它的子类InstrumentationTestRunner或AndroidJUnitRunner。

方式是在AndroidManiFest.xml里面配置:

<instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:label="InstrumentationApp"
    android:targetPackage="com.instrumentation.app" >
</instrumentation>

如果是AS里,通过gradel配置更为方便:

defaultConfig {
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

app正常的启动使用的是默认的Instrumentation的对象,在Activity类中其实是持有改对象的,通过反射的方式是可以看出来的:

Field mInstrumentation;
        Object value = null;
        try {
            mInstrumentation = Activity.class.getDeclaredField("mInstrumentation");
            mInstrumentation.setAccessible(true);
            value = mInstrumentation.get(this);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        Log.e("111", "Instrumentation: "+value.getClass().getName());  // Instrumentation: android.app.Instrumentation

自动化测试基本原理

Instrumentation框架下,测试应用程序可以精确控制应用程序。Instrumentation框架通过将主程序和测试程序运行在同一个进程来实现这些功能。

results matching ""

    No results matching ""