Search code examples
android-testingandroid-instrumentation

Android Espresso Turn OFF Cellular Data on Android Emulator through Runtime() not working


I am writing instrumentation test for a scenario where data is not available on android emulator (api 16 and api 23). I tried the following code to disable data,

@Test
public void disconnectData() throws IOException {
    String line;

    Process p = Runtime.getRuntime().exec("svc data disable");

    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((line = in.readLine()) != null) {
        System.out.println(line);
        Log.d("asdf", line);
    }

    in.close();
}

It does not do anything. Data is not disabled. It simply passed without error. There is no output.

If I run the same command from terminal using adb, it works:

adb -s emulator-5554 shell
svc data disable

Solution

  • Alternative solution is to use mockwebserver. E.g.,

       server.enqueue(new MockResponse()
                .setResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR)
                .setBody(getStringFromFile(getInstrumentation().getContext(), "login.json")));