Android-使用Junit单元测试
16lz
2021-01-25
Eclipse使用Junit单元测试
首先在项目的清单文件的如下位置添加:
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.drz.mobilesafe" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="android.test.runner" />
编写测试类继承 AndroidTestCase:注意方法要定义为public,不能是默认、protected、private public void testisToday() {
assertEquals(true, TimeTools.isToday(new Date()));
}
Android Studio使用Junit单元测试
参考资料: 在Android Studio中进行单元测试和UI测试 - 简书 http://www.jianshu.com/p/03118c11c199
默认情况下Android Studio已经添加的junit单元测试的库,所以这里可以直接省略该步。 功能类写好之后,直接在功能类文件中右键:
然后在测试方法中编写测试代码:一般使用断言进行结果判断
/**
* Created by drz on 2016/3/8.
*/
public class VolleyUtilsTest extends TestCase {
@Test
public void testGetInstance() throws Exception {
Context context = getInstrumentation().getContext();
RequestQueue requestQueue = VolleyUtils.getInstance(context);
assertNotNull(requestQueue);
}
}
关于测试中需要使用安卓上下文环境,需要添加支持Instrumentation测试 其中 Espresso,用于运行功能UI测试的框架。 修改module的build.gradle: apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.example.testing.testingexample"
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName "1.0"
//ADD THIS LINE:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
//ADD THESE LINES:
packagingOptions {
exclude 'LICENSE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0' //← MAKE SURE IT’S 22.0.0
testCompile 'junit:junit:4.12'
//ADD THESE LINES:
androidTestCompile 'com.android.support.test:runner:0.2'
androidTestCompile 'com.android.support.test:rules:0.2'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
}
配置完成之后点击Syc Now,之后就可以使用 Context context = getInstrumentation().getContext();获取上下文对象,同时注意 appcompat-v7库的版本不能高于22.0.0,否则会报告冲突。
更多相关文章
- android UiAutomator一个完整的个人信息修改测试用例
- Gradle 打不同的安装包
- Android之选项菜单和上下文菜单解析
- Android(安卓)插件化原理 完胜360插件框架 技术实战
- Android中常用的优秀开源框架
- 关于Android(安卓)火车票查询App
- Android(安卓)HIDL lshal
- Android四大组件之Intent
- android 渠道包自动化测试流程图