您的位置:首页 > 移动开发 > Android开发

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

2016-04-17 10:40 615 查看
build.gradle中添加依赖

dependencies {
compile 'com.android.support:appcompat-v7:23.2.1'
testCompile 'junit:junit:4.12'
}


添加以下,使用模拟环境代替真实环境

android {
testOptions {
unitTests {
returnDefaultValues = true
}
}
}


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);
}
}


注意上面代码继承的是 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);
}
}


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

源码分析

先介绍坑,即 AndroidTestCase 的 getContext()

public void setContext(Context context) {
mContext = context;
}

public Context getContext() {
return mContext;
}


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

成功方法,即ActivityTestCase 的 getInstrumentation().getContext()

public Context getContext() {
return mInstrContext;
}
//初始化时获得了Context
final 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;
}


上述源码清晰的说明了context赋值的过程,所以这种方式可以获得context值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: