Android Studio中使用junit4测试框架中的坑

来源:互联网 发布:seo网站分析案例 编辑:程序博客网 时间:2024/05/29 09:31
  • build.gradle中添加依赖
dependencies {    compile 'com.android.support:appcompat-v7:23.2.1'    testCompile 'junit:junit:4.12'}
  • 1
  • 2
  • 3
  • 4
  • 添加以下,使用模拟环境代替真实环境
android {    testOptions {         unitTests {            returnDefaultValues = true        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • Android Studio中不需要在清单文件中配置 instrumentation 和 uses-library
  • 测试代码主体部分(此方法也是趴Stack Overflow之中N久才得到的,感谢感谢)
public class TestBlackNumberDao extends ActivityTestCase{    public void testAdd() {        BlackNumberDAO dao = new BlackNumberDAO(getInstrumentation().getContext() );        boolean result = dao.insertDao("1888", "2");        assertEquals(true, result);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注意上面代码继承的是 ActivityTestCase ,获取上下文使用的是 getInstrumentation().getContext() ,使用这个方法完全可以获得测试结果。

  • 这里介绍坑之所在(调试好久才得到结果,惭愧惭愧)
public class TestBlackNumberDao extends AndroidTestCase{    public void testAdd() {        BlackNumberDAO dao = new BlackNumberDAO(getContext() );        boolean result = dao.insertDao("1888", "2");        assertEquals(true, result);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

上面代码是很多资料上写的方式,eclipse中完全可以使用上面所用得到测试结果,不过在Android Studio中会出现一个问题,那就是getContext()方法会返回null,即根本得不到上下文context,结果就是报出空指针异常bug。


源码分析

  • 先介绍坑,即 AndroidTestCase 的 getContext()
public void setContext(Context context) {    mContext = context;}public Context getContext() {    return mContext;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

查看源码可以得到上述部分,得知mContext由setContext方法进行赋值,但是没有一个地方有调用setContext方法,所以getContext方法的返回值自然就是null了。

  • 成功方法,即ActivityTestCase 的 getInstrumentation().getContext()
public Context getContext() {    return mInstrContext;}                                       //初始化时获得了Contextfinal void init(ActivityThread thread, Context instrContext, Context appContext, ComponentName component, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection) {     mThread = thread;     mMessageQueue = mThread.getLooper().myQueue();     mInstrContext = instrContext;   //here is context     mAppContext = appContext;     mComponent = component;     mWatcher = watcher;     mUiAutomationConnection = uiAutomationConnection; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

上述源码清晰的说明了context赋值的过程,所以这种方式可以获得context值

转载自:http://blog.csdn.net/yyg204731/article/details/51172111