Reputation: 131
I am writing Instrumentation tests for my app on Android Studio 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.
Upvotes: 13
Views: 3556
Reputation: 399
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)
Upvotes: 15
Reputation: 924
I recently ran into a similar issue. We resolved it by using dependency injection, injecting the logic as a dependency. You can either inject the WifiManager
service, which is slightly risky because it can be null, or you can inject something that handles the logic.
To simplify differences between Java/Kotlin and DI library of choice, this solution is pseudocode:
public class AppHelper {
public boolean isNetworkConnected(Context context) {
// Do your check
return isConnected;
}
}
public class SomeActivity extends Activity {
@Inject
AppHelper appHelper;
private void doNetworkStuff() {
boolean connected = appHelper.isNetworkConnected(this);
// implement your logic
}
}
From there, you can mock or manipulate an instance of AppHelper
to acheive your desired result.
Edit: For the record, I do not condone network operations be done in an Activity
. This is just for simplicity of getting the idea across.
Upvotes: 0