Reputation: 28188
I want to write automated tests to run on the emulator that verify that my app behaves correctly when the network connection is spontaneously dropped. To do so, I'd like to write tests like the following:
I have seen various stackoverflow answers that address this by suggesting manually disabling the network connection from the host PC via the command line. This cannot be not automated by a test that is running on the emulator, because the emulator has no access to its host PC. And running the commands in a host PC shell script would be very difficult to attempt to automatically synchronize with an emulator test.
Alternately I've seen answers that suggest manipulating the emulator's network settings, which apparently don't actually disable access, they only cause explicit connectivity checks like networkInfo.isConnected()
to report a disconnected state. They still allow bidirectional communication. (E.g., when emulator network access is disabled, the browser is still fully functional.)
Has anyone been able to construct automated tests that run on the emulator and actually turn on and off network access as needed mid-test?
Upvotes: 5
Views: 4065
Reputation: 28188
There is presently no way to truly disable network access programmatically from within a unit test. I filed an enhancement request for this issue.
Upvotes: 3
Reputation: 28717
If you're not averse to invoking an undocumented method, you can do the following to turn off / on the data connection.
public void enableData(Context context, boolean enable) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Method m = cm.getClass().getDeclaredMethod("setMobileDataEnabled", boolean.class);
m.invoke(cm, enable);
} catch (Exception e) {
}
}
Upvotes: 1