How to make android:usesCleartextTraffic="true" only for instrumentation tests?

Viewed 8593

I'm using RESTMock for my instrumentation tests, but it only works if I set usesCleartextTraffic to true in my manifest. I only want that to be true for instrumentation tests, though. Is there a way to do that?

I tried creating a new manifest file in the androidTest folder. The tests run but they fail like usesCleartextTraffic is still false.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="my.package">

    <application android:usesCleartextTraffic="true" />

</manifest>

I know that RESTMock supports https starting from version 0.3.2, but I'd rather not have to deal with it. I actually followed their guide and ended up with this error from OkHttp3:

java.lang.AssertionError: java.security.NoSuchAlgorithmException: The BC provider no longer provides an implementation for KeyPairGenerator.RSA. Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.

Any ideas?


EDIT:

I followed this answer and moved this manifest I created to the debug source folder and then it worked. Now the android:usesCleartextTraffic="true" option is only applied to my debug build, which is used by the instrumentation tests, so it works, but it still doesn't feel like the proper solution.

1 Answers

For me the solution is to add a simple AndroidManifest.xml in androidTest/AndroidManifest.xml. This is also mentioned in the answer you reference, but in that case it didn't work because old tooling didn't merge this AndroidManifest.xml.

So, inside androidTest directory, and next to java directory, I have the following:

~/source/my-library/src/androidTest develop*
❯ ls
AndroidManifest.xml java

With this AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.mypackage.mylibrary">

    <application
        android:usesCleartextTraffic="true" />

</manifest>
Related