1.Android 单元测试
2.AndroidTest获取context 为何为空
2.1 context可以获取到,但是为空
Context context = ApplicationProvider.getApplicationContext();
2.2 ApplicationProvider 源码
- 查看源码,跟网上的一样,InstrumentationRegistry.getInstrumentation().getTargetContext() 。
public final class ApplicationProvider {
private ApplicationProvider() {}
@SuppressWarnings("unchecked")
public static <T extends Context> T getApplicationContext() {
return (T)
InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
}
}
2.3 Instrumentation源码
- 我们查看Instrumentation 的源码,发现他mAppContext 也没初始化,获取当然就是空。
public class Instrumentation {
...
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;
}
public Context getTargetContext() {
return mAppContext;
}
...
}
3.正确获取方法
3.1 查看官网文档
3.2 创建application
- 在AndroidTest目录下创建Application。
public class TestApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
@RunWith(AndroidJUnit4.class)
public class MyTest {
@Test
public void test() {
Context context = ApplicationProvider.getApplicationContext();
}
}
|