Robolectric初学总结
前言
最近老大让研究下自动化测试,然后单元测试选择了Robolectric,UI测试选择啦UIAutomator
先来看看什么是Robolectric(官网)
Running tests on an Android emulator or device is slow! Building, deploying, and launching the app often takes a minute or more. That’s no way to do TDD. There must be a better way.
Robolectric is a framework that brings fast and reliable unit tests to Android. Tests run inside the JVM on your workstation in seconds. With Robolectric
可以看出普通的Android开发、测试是很耗时,而Robolectric使得Android测试代码可以运行在本地JVM环境中,所以测试速度很快。
1. 环境配置
在build.gradle添加:
android {
...
testOptions {
unitTests {
includeAndroidResources = true
}
}
...
}
dependencies {
...
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:4.1'
testImplementation 'org.robolectric:shadows-multidex:4.1'
...
}
2. 编写测试用例
在工程“src/test/java”下编写相应的包、类,在类名上添加“@RunWith(RobolectricTestRunner.class)
”,在方法名上添加“@Test
”
@RunWith(RobolectricTestRunner.class)
public class HttpTestDemo {
@Test
public void testHttpsRequest() {
}
}
3. 编译运行
在AndroidStudio的终端窗口,输入命令“
./gradlew test
”编译运行所有的用例
在AndroidStudio的终端窗口,输入命令“./gradlew testDebug –tests=”包.类.方法”
”编译运行指定的用例
ps:如果运行出现如下提示,可以登录
https://oss.sonatype.org/content/groups/public/
查找相同的目录org/robolectric/android-all/6.0.1_r3-robolectric-r1/android-all-6.0.1_r3-robolectric-r1.jar
把相应的jar包手动下载下来
然后把jar包放到~/.m2/repository/org/robolectric/android-all/6.0.1_r3-robolectric-r1目录下,重新运行就可以了
Downloading: org/robolectric/android-all/6.0.1_r3-robolectric-r1/android-all-6.0.1_r3-robolectric-r1.jar
from repository sonatype at https://oss.sonatype.org/content/groups/public/
Transferring 69884K from sonatype
4. 遇到的问题
4.1 找不到Robolectric类
提示“
cannot resolve symbol robolectrictestrunner
”、“cannot resolve symbol robolectric
”
先确认工程下“External Libraries”已经有Robolectric相关的jar了,并确认是在“src/test/java”下编写测试用例
如果还不行,可以尝试把AndroidStudio更新到最新版本
4.2 运行时依赖Android相关设置
在用例运行时可能会用到工程中原有类的方法、属性,而这些方法、属性又与Android系统环境有关,则可以通过Robolectric的
shadow class
来替换原来的类方法、属性,如果是构造方法则需要使用“public void __constructor__
”
替换Aapplication:
自定义“CustomMyApplication”继承“ShadowApplication”,加上注解“@Implements(MyApplication.class)”,从而与原来的“MyApplication”关联
再在要重写的方法上添加“@Implementation”
最后在测试用例类上添加“@org.robolectric.annotation.Config(shadows = {CustomMyApplication.class})”
@Implements(MyApplication.class)
public class CustomMyApplication extends ShadowApplication {
@Implementation
public void onCreate() {
}
}
@RunWith(RobolectricTestRunner.class)
@org.robolectric.annotation.Config(shadows = {CustomMyApplication.class})
public class TestDemo {
@Test
public void test() {
}
}
4.3 不能识别资源文件dimens.xm配置的值
提示错误“
layout/activity_main.xml line #-1 (sorry, not yet implemented): Can't convert to dimension: type=0x1
”
这是由于配置的数值有小数点导致,需要修改为整数
4.4 添加log信息
添加“
ShadowLog.stream = System.out;
”,就可以进行log输出了