阅读 312

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();
    }
}
复制代码
文章分类
Android