使用网上所说的AndroidTestCase的getContext方法,获取到的context为空。为什么这个方法获取的context为空,或者有什么其他的在单元测试中获取context的方法?
这是代码:
public class UtilsTests extends AndroidTestCase{
private String dateTime = "2016-6-12 5:33:32";
private Context context;
@Before
public void setUp() throws Exception {
super.setUp();
context = getContext();
}
@Test
public void testGetPath() throws Exception {
assertEquals(getContext(),null);
}
}
断言判断出来context为null
要不你试试自己封装一个MyApplication类继承自Application
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
}
public static Context getContext(){
return context;
}
}
在你的setUp()方法中调用MyApplication的getContext方法就可以拿到application级的context.
如果你要activity级 的context,要另想办法
你可以试着通过extend InstrumentationTestCase
再调用getInstrumentation().getContext()
来获取Context
。
在stackoverflow找到了解决的办法,Context context = new MockContext();
附上链接:http://stackoverflow.com/questions/28960898/getting-context-in-androidtestcase-or-instrumentationtestcase-in-android-studio
对于AndroidTestCase,虽然它提供了getContext()方法获取Context对象,但就一个新的默认的AndroidTestCase类实例,它的成员变量mContext是没有被初始化赋值的,所以getContext()取出的Context对象是null,AndroidTestCase提供setContext(Context context)方法来给mContext赋值,以上,可以看AndroidTestCase类的源码来分析。对于一般的AndroidTestCase可能不好setContext,可以考虑另一种方式获取Context,反射调用ServiceTestCase进行类型转换得到。
public class MyTest extends AndroidTestCase {
private Context getTestContext() {
try {
Method getTestContext = ServiceTestCase.class.getMethod("getTestContext");
return (Context) getTestContext.invoke(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
将你的代码放在module-name/src/androidTest/java/路径下,估计是你的代码放在module-name/src/test/java/路径下了