4

Has anyone had any luck toggling the device network in the middle of an instrumentation test? I've found some hacky outdated solutions that are no longer supported such as this one.

I can't seem to find any recent answers to this problem. I'm sure this is a common testing scenario for many applications. Thanks in advance!

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
John A Qualls
  • 739
  • 1
  • 6
  • 17
  • Interesting. I think you can change the wifi SSID which the device connects to programmatically [as suggested here](https://stackoverflow.com/a/8818490/3145960). However, not very familiar with how you can do that during an instrumentation test. – Reaz Murshed Oct 15 '19 at 23:49
  • 2
    Thanks for the quick response! Hmm I wonder if there is something I can do with that option. I'll take a look. – John A Qualls Oct 15 '19 at 23:53
  • 1
    You could structure your test using `UIAutomator` and [`openQuickSettings()`](https://developer.android.com/reference/androidx/test/uiautomator/UiDevice.html#openQuickSettings()), then toggling airplane mode that way. Related reading [here](https://stackoverflow.com/questions/22681980/quick-setting-through-uiautomator). It's not exactly the best solution, but you usually have control over the device/emulator you run your tests on. – Sandi Oct 16 '19 at 00:01
  • This looks like exactly what I need. I'll give it a try and update this thread with my findings. Thanks! – John A Qualls Oct 16 '19 at 00:03

1 Answers1

1

Alright, below is a solution that I came up with to enable/disable the network during an instrumented test. Thank you for the reference to UiAutomator Sandi!

fun clickAirplaneMode(instrumentation: Instrumentation, targetContext: Context) {
    UiDevice.getInstance(instrumentation).run {
        targetContext.packageManager.getLaunchIntentForPackage("com.android.settings")?.let {intent ->
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            targetContext.startActivity(intent)
            findObject(UiSelector().textContains("Network")).clickAndWaitForNewWindow()
            findObject(UiSelector().textContains("Airplane")).click()
        }
    }
}
John A Qualls
  • 739
  • 1
  • 6
  • 17