Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internet access in Instrumented Test

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
  }
}
like image 910
asclepix Avatar asked Aug 31 '26 09:08

asclepix


1 Answers

You might be missing this on your manifest

<uses-permission android:name="android.permission.INTERNET" />
like image 122
Nehemias G Miranda Avatar answered Sep 04 '26 03:09

Nehemias G Miranda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!