Android Instrumented测试为何用主Manifest?如何仅测试启用明文流量?
Android Instrumented测试中Manifest相关问题解答
一、app-debug-androidTest.apk与app-debug.apk的关系
app-debug.apk是主应用的Debug安装包,包含业务代码、资源及主AndroidManifest.xml配置,是Instrumented测试的目标运行环境,必须先安装才能执行测试。app-debug-androidTest.apk是专属测试包,仅包含Instrumented测试用例代码、测试资源及测试AndroidManifest.xml,无法独立运行,必须依附主应用包安装。- 测试运行时,系统会同时部署两个APK:主应用提供被测逻辑和运行上下文,测试包通过Android测试框架调用主应用代码执行测试用例。
二、让测试Manifest配置生效的解决方案
方法1:用Manifest合并规则强制覆盖属性
默认情况下,测试Manifest的application属性不会自动覆盖主Manifest的同名属性,需添加tools:replace指令明确合并规则:
修改src/androidTest/AndroidManifest.xml如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic" /> </manifest>
tools:replace会告诉Manifest合并工具,当测试配置与主配置冲突时,优先使用测试包的属性值。
方法2:使用测试专属网络安全配置(更安全)
如果不想全局开启明文流量,可仅对localhost/127.0.0.1放行,更符合安全规范:
- 在
src/androidTest/res/xml目录下创建network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">localhost</domain> <domain includeSubdomains="true">127.0.0.1</domain> </domain-config> </network-security-config>
- 在测试Manifest中引用该配置:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:networkSecurityConfig="@xml/network_security_config" /> </manifest>
这种方式仅允许测试环境下对本地地址的明文请求,避免全局开启明文流量带来的安全风险。
内容的提问来源于stack exchange,提问作者JonasVautherin
相关产品推荐
相关产品推荐

