android之在 AndroidManifest 元数据中指定自定义 RunListener 不起作用
目标
有一个自定义RunListener使用 Espresso 运行 Android 仪器测试时,对测试失败执行自定义操作。
tl;博士
InstrumentationInfo.metaData是 null ,即使 ApplicationInfo.metaData有我的信息。为什么?
迄今为止的进展
我可以让我的 RunListener 使用以下 adb 命令:
adb shell am instrument -w -e listener com.myproject.test.runlisteners.CustomRunListener -e class com.myproject.test.ui.HomeActivityTest#testWillFail com.myproject.test/android.support.test.runner.AndroidJUnitRunner
这是在 AndroidJUnitRunner here 的文档中指定的.
但是,该文档还指出可以在 AndroidManifest.xml 中指定 RunListener元数据元素。到目前为止,我还没有成功地让它发挥作用。
AndroidManifest.xml
我将以下内容添加到我的 <application> 中main/AndroidManifest.xml 中的元素:
<meta-data
android:name="listener"
android:value="com.myproject.test.runlisteners.CustomRunListener" />
这没有任何效果。通过各种方式,我发现这些代码行( AndroidJUnitRunner 和 RunnerArgs 使用它们从 list 中获取自定义元数据参数)
InstrumentationInfo instrInfo = pm.getInstrumentationInfo(
getComponentName(), PackageManager.GET_META_DATA);
Bundle b = instrInfo.metaData;
...给我返回 null bundle 。
我注意到生成的debug/AndroidManifest.xml没有我的元数据标签,因此,作为实验,我还将其添加到我的 androidTest/AndroidManifest.xml 中文件。看起来像这样:
<application
android:name=".BaseApplication">
<meta-data
android:name="listener"
android:value="com.sirius.test.runlisteners.CustomRunListener" />
</application>
...然后出现在生成的 debug/AndroidManifest.xml 中像这样:
<application android:name="com.myproject.BaseApplication" >
<meta-data
android:name="listener"
android:value="com.sirius.test.runlisteners.CustomRunListener" />
<uses-library android:name="android.test.runner" />
</application>
这也没有任何效果。
另一个实验
我创建了一个名为 CustomAndroidJUnitRunner 的自定义测试运行程序它扩展了 AndroidJUnitRunner 只是为了在后台达到峰值。如果我这样做:
ApplicationInfo ai = packageManager.getApplicationInfo(
getComponentName().getPackageName(), PackageManager.GET_META_DATA);
Bundle b = ai.metaData;
Object o = b.get("listener");
Log.d(TAG, "listener=" + o.toString());
...logcat 会说:
D/CustomAndroidJUnitRunner: listener=com.myproject.test.runlisteners.CustomRunListener
所以,ApplicationInfo.metaData有它。为什么不InstrumentationInfo.metaData ?
请您参考如下方法:
有时,直到您花时间彻底解释所有内容后,您才最终了解问题所在。解决方案是将其添加到 <manifest>元素:
<instrumentation
android:name="com.myproject.test.runner.CustomAndroidJUnitRunner"
android:functionalTest="false"
android:handleProfiling="false"
android:label="Tests for com.myproject"
android:targetPackage="com.myproject">
<meta-data
android:name="listener"
android:value="com.myproject.test.runlisteners.CustomRunListener" />
</instrumentation>
我刚刚复制粘贴了 <instrumentation>生成的 debug/AndroidManifest.xml 中的元素文件。
最初我有点困惑,因为 CustomAndroidJUnitRunner和com.myproject在 Android Studio 中以红色突出显示。但一切都编译得很好。
我希望这对其他人有帮助!
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



