I am writing Instrumentation tests for my app on Android Studios testing on an emulator with Espresso. I need to disable the internet from within the test to make sure my error handling functionality works when the user does not have internet available. I've searched all over for an easy way to programmatically disable the internet from an emulated device. Here is the closest I've come, which does not work.
WifiManager wifiManager = (WifiManager) mActivityRule.getActivity().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
Even calling this in the @Before code block does nothing, and I also have the necessary privileges set in the AndroidManifest.xml file to change the wifi settings.
From a test we can easily run a command without root access:
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc data disable")
Took me a while to find it out, with all those answers and articles that suggest outdated solutions (wifiManager.setWifiEnabled is deprecated in API 29)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With