一.环境
Win7x64
Android studio 1.2.1.1
robolectric:3.0-rc2(官方文档的3.0无法下载)
二.步骤
1.build.gradle中dependencies添加如下依赖
testCompile "junit:junit:4.12"
testCompile 'org.robolectric:robolectric:3.0-rc2'
为保证依赖库能正常下载,在项目根目录下的build.gradle中添加如下
allprojects {
repositories {
jcenter()
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
mavenLocal()
mavenCentral()
}
}
2.修改BuildVariants 为 Unit Tests
3.修改测试源码目录androidTest为test
4.创建测试类,选择junit4
若弹出选择测试类保存位置选择框,请选择刚才重命名的test文件夹下
5.运行
在待运行测试类上右键
或者是
选择test运行,运行结果 保存在项目.\build\reports\tests目录下.
三.集成中的一些问题
1.Failed to Resolve org.robolectric, 参照步骤2解决,注意Robolectric版本。
2.java.lang.RuntimeException: build\intermediates\bundles\debug\AndroidManifest.xml not found or not a file; it should point to your project's AndroidManifest.xml
测试代码不要以junit方式运行,选用gradle方式运行
3.java.lang.RuntimeException: No 'constants' field in @Config annotation!
或java.io.FileNotFoundException: build\intermediates\manifests\full\AndroidManifest.xml
请在测试类名上添加注解@Config(constants = BuildConfig.class)
注意constants值必须为BuildConfig.class 否则会出现找不到AndroidMainifest.xml的问题.