Espresso 2.0 源码解析 (一)

源代码

之前其实我已经写过了Espresso2.0使用AS和Gradle执行用例的Sample,详细可以见Testerhome之前的帖子。其实接着我还是想看看Espresso的实现。所以就有了这篇文章,但是代码量太大,也来不及看,所以其实想一边写这篇文章一边看的。嗯。
下载之后导入即可看到下面的图示,证明你已经拿到了游戏中的第一个item。

espresso1
espresso1

慢慢看

接着我们先来看testrunner,单纯从名字来看其实感觉是不是Espresso自己的runner呢,现在还不知道,我们打开所有的目录大概浏览下。如下


espresso2
espresso2

这个时候我们眼前一亮,看到了一个熟悉的名字GoogleInstrumentation,点击进去一看

public class
GoogleInstrumentation
extends ExposedInstrumentationApi 

那么好吧,我表示不明白extends这个东西有啥用,那么继续去看了ExposedInstrumentationApi。整个代码还是很简单的。

package com.google.android.apps.common.testing.testrunner;

import android.app.Activity;
import android.app.Fragment;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;


/**
 * Exposes select hidden android apis to the compiler.
 * These methods are stripped from the android.jar sdk compile time jar, however
 * are called at runtime (and exist in the android.jar on the device).
 *
 * This class is built with neverlink=1 to ensure it is never actually included in
 * our apk.
 */
public abstract class ExposedInstrumentationApi extends Instrumentation {
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
          throw new RuntimeException();
    }

    public void execStartActivities(Context who, IBinder contextThread,
            IBinder token, Activity target, Intent[] intents, Bundle options) {
          throw new RuntimeException();
    }

    public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Fragment target,
        Intent intent, int requestCode, Bundle options) {
          throw new RuntimeException();
    }

  public ActivityResult execStartActivity(
      Context who, IBinder contextThread, IBinder token, Activity target,
      Intent intent, int requestCode) {
          throw new RuntimeException();
  }

}

那么这里我们看到了其实应该使用了Instrumentation下面的方法,所以继续调查了execStartActivity这个方法,发现该方法其实在MonitoringInstrumentation下面,这个类我们可以认为是Instrumentation的一个扩展,那么在下面我们找到了这里使用的几个方法。

但是在Android文档中并没有对该方法有什么描述,我表示就很焦虑了。接着我继续Google了这个方法到底要干嘛。突然发现了如下的知识,嗯
以下是StartActivity方法的将Activity调起来的部分过程

从Activity类的startActivity()方法开始,这个方法会调用Activity类中的public void startActivityForResult()方法 startActivityForResult()方法会调用Instrumentation类中的public ActivityResult execStartActivity()方法,这个方法加上了{@hide}对外是不可见的

这里眼前又一亮,因为我们看到了在启动Activity的过程中第二步就会去调用这个execStartActivity方法,而且这个方法本身是hide的。那么到这里,我们终于明白了,为什么ExposedInstrumentationApi文件夹目录叫做hidden了。然后我们也理解了源码中的第一句话。

  • Exposes select hidden android apis to the compiler. 由于该方法本身是隐藏的,所以我们需要暴露出来以之后被使用。
    到这里,我们差不多知道ExposedInstrumentationApi是干什么的了,那么接着我们继续来看GoogleInstrumentation。

继续一步一步

Instrumentation方法下原本就有onCreate方法,而在这里Espresso重写了该方法。如下

  @Override
  public void onCreate(Bundle arguments) {
    Log.i(LOG_TAG, "Instrumentation Started!");
    tryLoadingIntentSpy();
    InstrumentationRegistry.registerInstance(this);
    ActivityLifecycleMonitorRegistry.registerInstance(lifecycleMonitor);

    handlerForMainLooper = new Handler(Looper.getMainLooper());
    mainThread = Thread.currentThread();
    executorService = Executors.newCachedThreadPool();
    Looper.myQueue().addIdleHandler(idleHandler);
    super.onCreate(arguments);
  }

这个方法开始我看着还是觉得很奥妙的。比如这里的tryLoadingIntentSpy();,当然这个方法还是很重的,我们继续来看实现

  private void tryLoadingIntentSpy() {
    // Wouldn't it be easier to call IntentSpyImpl.getInstance() and be done with it? We don't do
    // this to avoid bringing in common lib dependencies (which cause painful conflicts with some
    // android projects) into G3ITR. Instead, we try to load IntentSpyImpl via reflection. Projects
    // that don't have intento in deps will not have IntentSpyImpl included at runtime (i.e. we
    // proceed as normally) and leave intentSpy as null (to be checked later). However, if it is
    // loaded, we can call any method of IntentSpy.
    try {
      Class<?> c = Class.forName("com.google.android.apps.common.testing.intento.IntentSpyImpl");
      intentSpy = (IntentSpy) c.getMethod(
          "load", Context.class, Context.class).invoke(null, getTargetContext(), getContext());
      Log.i(LOG_TAG, "IntentSpyImpl loaded");
    } catch (ClassNotFoundException cnfe) {
      Log.i(LOG_TAG, "IntentSpyImpl not loaded: " + cnfe.getMessage());
    } catch (NoSuchMethodException nsme) {
      throw new RuntimeException(
          "IntentSpyImpl is available at runtime, but getInstance method was not found", nsme);
    } catch (SecurityException se) {
      throw new RuntimeException(
          "IntentSpyImpl is available at runtime, but calling it failed.", se);
    } catch (IllegalAccessException iae) {
      throw new RuntimeException(
          "IntentSpyImpl is available at runtime, but calling it failed.", iae);
    } catch (IllegalArgumentException iare) {
      throw new RuntimeException(
          "IntentSpyImpl is available at runtime, but calling it failed.", iare);
    } catch (InvocationTargetException ite) {
      throw new RuntimeException(
          "IntentSpyImpl is available at runtime, but calling it failed.", ite);
    }
  }

其实注释已经写的很清楚了,我不知道我理解的对不对。从实现上其实就是为了避免各种错误所以使用了反射的机制来获取这个运行的Intent,拿到这个intentSpy之后,我们就可以使用下面的方法了,不过稍等,这个intentSpy又是个什么鬼。我们看上面的目录结构,其实可以看到有两个interface。

其实简单看了下这个interface,就是实现了若干方法,也是为了拿到Activity的一些东西,先不管了。继续往下看。

    InstrumentationRegistry.registerInstance(this);
    ActivityLifecycleMonitorRegistry.registerInstance(lifecycleMonitor);
    

这两个其实查了下Android文档,其实就是两个监听的方法。描述类似

Records/exposes the instrumentation currently running and stores a copy of the instrumentation arguments Bundle in the registry.
那么在onCreate中调用也是可以理解,肯定后续会使用到。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,444评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,867评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,157评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,312评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,673评论 3 289
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,802评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,010评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,743评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,470评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,696评论 2 250
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,187评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,538评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,188评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,127评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,889评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,741评论 2 274

推荐阅读更多精彩内容