3

I'm trying to reach one of our servers in an Android Instrumented Test. I'm running the test on a device with Android 10 and I obtain the following Exception:

Permission denied (missing INTERNET permission?)

To avoid this I've tried (I'm using kotlin)

@Rule
@JvmField
var runtimePermission = GrantPermissionRule.grant(Manifest.permission.INTERNET)

but in this case I've got thi error:

junit.framework.AssertionFailedError: Failed to grant permissions

Even the following code has no success:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        getInstrumentation().getUiAutomation().executeShellCommand(
                "pm grant " + context.getPackageName()
                        + " android.permission.INTERNET");
}

Is it possible to achieve my goal?

[UPDATED] Here is a minimal test:

class Minimal {

@Rule
@JvmField
var runtimePermission: GrantPermissionRule = GrantPermissionRule.grant(Manifest.permission.INTERNET)

@Test
fun minimalReproducible() {

    val buffer = CharArray(2000)
    val url = URL("https://example.net/new-message.php")
    val connection = url.openConnection() as HttpsURLConnection
    connection.requestMethod = "POST"

    val urlParameters: String = ""      // buildParameterUrlString(params)

    connection.doOutput = true
    val outputStream = DataOutputStream(connection.outputStream)
    outputStream.writeBytes(urlParameters)
    outputStream.flush()
    outputStream.close()
    val responseCode = connection.responseCode
  }
}
asclepix
  • 7,971
  • 3
  • 31
  • 41

1 Answers1

1

You might be missing this on your manifest

<uses-permission android:name="android.permission.INTERNET" />
  • Where is the Manifest for the tests? – asclepix Oct 06 '20 at 15:52
  • 1
    This response can help you create your manifest for the tests if you don't have one yet https://stackoverflow.com/a/27884436/11611305 – Nehemias G Miranda Oct 06 '20 at 16:02
  • It works! Please, expand the answer saying where to put the Manifest for tests; in fact, I didn't know it was possible to have a Manifest for the tests. – asclepix Oct 07 '20 at 15:24
  • Test manifest is not needed. You must add the permission to the module manifest. This is a common error when creating modules, when modules have no permissions and app has all the permissions. Best practice is to declare the needed permissions in every module: the compiler will then make the merged Manifest. – Corbella Jul 21 '23 at 14:58