Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing internet connectivity error handling in Android Studios with Espresso on Emulator

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.

like image 404
Drifting Avatar asked Sep 29 '16 00:09

Drifting


1 Answers

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)

like image 164
lllyct Avatar answered Oct 15 '22 10:10

lllyct