Blog
Blog copied to clipboard
Android自动化测试与持续集成
Android自动化测试与持续集成
标签(空格分隔): Android
又来搞Android自动化了,上篇文章总结的还是可以的,一晚上就把runner跑起来了。
之前写的时候还没有接触到Android自动化测试,只是搭了个架子,每次Push的时候编译一个APK出来。
现在网上讲Android单元测试的文章简直丰富的不得了,但是自动化单元测试的好像没见多少,可能是因为太简单了吧。
今天在运行单元测试的时候终于让我碰上了一个坑。
首先我的单元测试使用了Robolectric。
Robolectric有两个类,RobolectricTestRunner.class
和RobolectricGradleTestRunner.class
https://github.com/robolectric/robolectric的Readme中给出的使用方法是
@RunWith(RobolectricTestRunner.class)
但是我们项目中却使用了
@RunWith(RobolectricGradleTestRunner.class)
根据代码注释
/**
- Test runner customized for running unit tests either through the Gradle CLI or
- Android Studio. The runner uses the build type and build flavor to compute the
- resource, asset, and AndroidManifest paths. *
- This test runner requires that you set the 'constants' field on the @Config
- annotation (or the org.robolectric.Config.properties file) for your tests. */
RobolectricGradleTestRunner
应该更好的支持了Android Studio和Gradle。而且RobolectricGradleTestRunner
继承自RobolectricTestRunner
,所以最好还是使用RobolectricGradleTestRunner
。
我的应用使用了自己的字体,Application启动的时候从assets文件夹中读取,然后问题出现了,运行单元测试,提示找不到字体。
然而使用RobolectricTestRunner
的另一个单元测试是可以运行的。
起初我以为是代码混淆的时候压缩资源把字体文件移除掉了。结果发现并不是,单元测试时读取字体文件的文件夹都没有生成。
把RobolectricGradleTestRunner
换成RobolectricTestRunner
也不行。
然后去找这个文件夹的资料: app/build/intermediates/bundles/assets
找到这么一个描述 http://stackoverflow.com/a/27108547/3819519
The "intermediates" folder contains individual files that are created during the build process and which are eventually combined to produce the "apk" file.
然后恍然大悟,原来需要先build,再test。跟我原来想的不一样,我以为先进行单元测试,单元测试失败以后就不用build了,但是单元测试的运行是需要先build的。
还有一个小问题到现在也没有解决,使用Kotlin编写单元测试,@Config(...)
Config中不能配置sdk,提示sdk需要是IntArray,使用Java写一遍,然后使用Plugin转换成Kotlin也不行。
刚写完顺手又查了一下,换了关键词,发现了Kotlin配置Robolectric sdk的解决方案。
http://stackoverflow.com/questions/34773958/kotlin-and-argumentcaptor-illegalstateexception
@Config(sdk = intArrayOf(21), constants = BuildConfig::class)
看来还是得从基础学起啊。
再次修改,发现之前单元测试需要Build是Android项目中读取了一个资源文件的操作没有解耦。正确的做法还是应该先单元测试,单元测试没有问题才考虑部署,如果单元测试依赖于编译APK,那就说明单元测试的部分没有完全解耦。