I am trying to uses OkHttp in some Android instrumented tests, but I get the following error:
java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy
For API 28 and higher, the documentation says that android:usesCleartextTraffic
should be set in that case.
If I set android:usesCleartextTraffic="true"
in my main/AndroidManifest.xml
, then it works. But that is not what I want; I want to enable this only for tests.
So I created myproject/app/src/androidTest/AndroidManifest.xml with the following content:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:usesCleartextTraffic="true" />
</manifest>
And it does what I expect: the generated instrumented apk (./app/build/intermediates/apk/androidTest/debug/app-debug-androidTest.apk) has an AndroidManifest that correctly sets usesCleartextTraffic
(I checked with apktool
directly in the app-debug-androidTest.apk.
But it seems like it doesn't matter, because anyway at runtime it will somehow rely on the AndroidManifest of the main app: ./app/build/intermediates/apk/debug/app-debug.apk. If I set usesCleartextTraffic=true
in the main AndroidManifest, then it works. But that's not what I want; I want it only for the instrumented tests!
What is the relation between app-debug-androidTest.apk and app-debug.apk when running instrumented tests, and how to make the androidTest/AndroidManifest.xml have priority (or be merged) into the main one when running the instrumented tests?