Android Espresso 通过 Runtime() 关闭 Android 模拟器上的蜂窝数据不工作

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

我正在为 android 模拟器(api 16 和 api 23)上的数据不可用的场景编写仪器测试。我尝试了以下代码来禁用数据,

@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();
}

它什么都不做。数据未禁用。它只是毫无错误地通过了。没有输出。

如果我 运行 使用 adb 从终端执行相同的命令,它会起作用:

adb -s emulator-5554 shell
svc data disable

替代解决方案是使用 mockwebserver。例如,

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