AndroidTest 获取 context 的正确方法

1.Android 单元测试

2.AndroidTest获取context 为何为空

2.1 context可以获取到,但是为空

//这样可以获取context
Context context = ApplicationProvider.getApplicationContext();

2.2 ApplicationProvider 源码

  • 查看源码,跟网上的一样,InstrumentationRegistry.getInstrumentation().getTargetContext()
/**
 * Provides ability to retrieve the current application {@link Context} in tests.
 *
 * <p>This can be useful if you need to access the application assets (eg
 * <i>getApplicationContext().getAssets()</i>), preferences (eg
 * <i>getApplicationContext().getSharedPreferences()</i>), file system (eg
 * <i>getApplicationContext().getDir()</i>) or one of the many other context APIs in test.
 */
public final class ApplicationProvider {

  private ApplicationProvider() {}

  /**
   * Returns the application {@link Context} for the application under test.
   *
   * @see {@link Context#getApplicationContext()}
   */
  @SuppressWarnings("unchecked")
  public static <T extends Context> T getApplicationContext() {
    return (T)
        InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
  }
}

2.3 Instrumentation源码

  • 我们查看Instrumentation 的源码,发现他mAppContext 也没初始化,获取当然就是空。
public class Instrumentation {
...
    /*package*/ final void init(ActivityThread thread,
            Context instrContext, Context appContext, ComponentName component, 
            IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection) {
        mThread = thread;
        mMessageQueue = mThread.getLooper().myQueue();
        mInstrContext = instrContext;
        mAppContext = appContext;
        mComponent = component;
        mWatcher = watcher;
        mUiAutomationConnection = uiAutomationConnection;
    }

    //直接返回mAppContext
    public Context getTargetContext() {
        return mAppContext;
    }
...
}

3.正确获取方法

3.1 查看官网文档

  • 查看 AndroidJUnitRunner 文档。
  • 原来是需要在应用中 创建了 Application 的自定义子类,才可以用此方法获取context。
    在这里插入图片描述

3.2 创建application

  • 在AndroidTest目录下创建Application。


    在这里插入图片描述
public class TestApplication extends Application {
    private Context mContext;
    
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }
    
     public static Context getContext() {
        return mContext;
    }
}
  • 这时候获取就不为空啦。
@RunWith(AndroidJUnit4.class)
public class MyTest   {
    @Test
    public void test() {
        Context context = ApplicationProvider.getApplicationContext();
        //也可以
        //TestCaseApplication.getContext();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • @Author:彭海波 前言 单元测试(又称为模块测试, Unit Testing)是针对程序模块(软件设计的最小...
    海波笔记阅读 5,049评论 0 52
  • 官方文档链接:https://developer.android.google.cn/training/testi...
    lanceJin阅读 1,027评论 0 0
  • Instrumentation Test Class VS JUnit Test Class 上面的代码给出的...
    chandarlee阅读 6,207评论 0 53
  • 自动化测试麻烦吗?说实在,麻烦!有一定的学习成本。但是,自动化测试有以下优点: 节省时间:可以指定测试某一个act...
    mahongyin阅读 904评论 0 1
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,624评论 28 53