Android Instrumentation测试离线案例

cld4siwp  于 2023-09-29  发布在  Android
关注(0)|答案(7)|浏览(154)

在我的仪器测试中,我使用Robotium。大多数情况下,我能够测试一切,但离线情况。
一旦我禁用数据(使用adb,F8快捷键在模拟器等。...)测试断开。它在设备/模拟器中继续,但没有报告结果。
所以,我有一个想法,只把应用程序在离线模式,而不是整个设备。问题是我不知道怎么...
使用iptablesApi我需要root我的设备。我读到过Mobiwol应用程序使用某种VPN来限制应用程序的互联网访问,而不需要root设备。

问题Mobiwol应用如何阻止每个应用的互联网连接?或者有其他方法可以离线测试apk?
2014年12月30日编辑

我忘了说,我可以离线运行测试,但我必须在设备处于离线状态时开始测试。目前,我将我的测试分为离线和在线测试。在运行ONLINES之后,我执行著名的adb kill-serveradb start-server。之后我执行OFFLINES。

wgx48brx

wgx48brx1#

只是提出一些建议,因为这里似乎有不同的问题。1)如果你想做的只是在运行OFFLINE测试用例之前关闭数据,你可能想简单地尝试使用robotium本身来完成。
示例:对于WiFi:

  1. WifiManager wifi=(WifiManager)solo.getCurrentActivity().getSystemService(Context.WIFI_SERVICE);
  2. wifi.setWifiEnabled(false);

对于移动的数据(使用反射):

  1. ConnectivityManager dataManager=(ConnectivityManager)solo.getCurrentActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
  2. Method dataClass = ConnectivityManager.class.getDeclaredMethod(“setMobileDataEnabled”, boolean.class);
  3. dataClass.setAccessible(true);
  4. dataClass.invoke(dataManager, true);

您可以在运行OFFLINE套件中的单个测试用例之前,在setup()方法中执行上述两个调用。完成OFFLINE套件中的所有测试用例后,您可以在最后的teardown()方法中启用WiFi/DATA。
2)看看你在OP中发布的应用程序,似乎它:

  • 根据操作系统版本使用ipTables
  • 根据UID为所有需要WiFi/数据的应用程序创建脚本头
  • 应该从包管理器中获取设备上安装的应用程序列表沿着任何隐藏的应用程序等。
  • 再次根据用户选择的黑名单执行脚本,并使用用户所需的规则覆盖ipTable中的现有规则。

很肯定,虽然必须有相当困难的代码所有这些..听起来容易得多的形式要点。
希望这对你有所帮助。
附言:如果你确实想出了一些东西,请发布一个更新的答案,想知道你是如何使它工作的

展开查看全部
mfuanj7w

mfuanj7w2#

在花了几个小时试图做类似于user2511882的解决方案,我仍然有一个异常,因为缺少权限(是的,“修改系统设置”权限被激活)。
最后我用UI automator来做:

  1. public static void setAirplaneMode(boolean enable)
  2. {
  3. if ((enable ? 1 : 0) == Settings.System.getInt(getInstrumentation().getContext().getContentResolver(),
  4. Settings.Global.AIRPLANE_MODE_ON, 0))
  5. {
  6. return;
  7. }
  8. UiDevice device = UiDevice.getInstance(getInstrumentation());
  9. device.openQuickSettings();
  10. // Find the text of your language
  11. BySelector description = By.desc("Airplane mode");
  12. // Need to wait for the button, as the opening of quick settings is animated.
  13. device.wait(Until.hasObject(description), 500);
  14. device.findObject(description).click();
  15. getInstrumentation().getContext().sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
  16. }

您需要在androidTest清单文件中包含ACCESS_NETWORK_STATE:

  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

别忘了在测试后禁用它。
如果您有英语以外的其他语言,您需要将“飞行模式”更改为您的语言文本。因为我有几个翻译,我从一个resource字符串中读取它。

展开查看全部
2fjabf4q

2fjabf4q3#

LinkedIn Test Butler有一个很棒的库,您可以通过简单的调用启用,禁用WiFi和移动的数据:

  1. TestButler.setGsmState(false);
  2. TestButler.setWifiState(false);

此库的主要优点是它不需要在您的清单中获得任何权限,有关更多详细信息,请参阅项目网站:
https://github.com/linkedin/test-butler

t9eec4r0

t9eec4r04#

抱歉,如果我过于简单化了,但是把手机/模拟器置于飞行模式怎么样?通过实际的用户界面。我就是这么做的。

mitkmikd

mitkmikd5#

使用@Illyct的解决方案(请投票支持他们的答案https://stackoverflow.com/a/64765567/191761

  1. InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")
  2. InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc data disable")
0s7z1bwu

0s7z1bwu6#

这里有一个解决方案,它使用UiAutomator从下拉状态栏中启用或禁用“飞行模式”,如果启用,则关闭所有网络。它适用于大多数Android操作系统版本,并使用用户Aorlinn(2019年10月12日)的部分答案。

app/build.gradle

  1. dependencies {
  2. androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
  3. }
AndroidManifest.xml

不需要额外的权限,甚至不需要<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />,因为UiAutomator只需要点击状态栏UI中的一个按钮。因此,应用程序不需要直接访问来修改设备的Wifi或移动的数据设置。

Kotlin

  1. import android.os.Build
  2. import android.provider.Settings
  3. import androidx.test.espresso.matcher.ViewMatchers.assertThat
  4. import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
  5. import androidx.test.uiautomator.By
  6. import androidx.test.uiautomator.UiDevice
  7. import androidx.test.uiautomator.UiObjectNotFoundException
  8. import androidx.test.uiautomator.Until
  9. import org.hamcrest.Matchers.`is`
  10. import org.junit.Assert
  11. import org.junit.Assume.assumeNoException
  12. import org.junit.Assume.assumeThat
  13. import java.io.IOException
  14. private var airplaneModeOn = 0
  15. private val OFF = 0
  16. private val ON = 1
  17. private var airplaneModeButtonPosition: Point? = null
  18. /**
  19. * Turn off the Internet connectivity by switching "Aeroplane mode" (flight mode) on. From:
  20. * https://stackoverflow.com/questions/27620976/android-instrumentation-test-offline-cases#68956544
  21. */
  22. @Test
  23. fun checkAppWillWork_withNoInternetConnection() {
  24. try {
  25. airplaneModeOn = getCurrentAirplaneModeSetting()
  26. } catch (e: Exception) {
  27. e.printStackTrace()
  28. assumeNoException("Cannot retrieve device setting of 'Airplane Mode'. Aborting the test.", e)
  29. }
  30. // Check that Airplane mode is off
  31. assertThat(airplaneModeOn, `is`(OFF))
  32. // Press the "Aeroplane mode" button on the 'Quick Settings' panel
  33. toggleAeroplaneModeButton()
  34. // Verify Airplane mode is on
  35. assumeThat("Cannot change the 'Aeroplane Mode' setting. Test aborted.", airplaneModeOn, `is`(ON))
  36. assertThat(airplaneModeOn, `is`(ON))
  37. // Do some tests when the Internet is down
  38. // Note: Switch the Internet back on in cleanup()
  39. }
  40. /**
  41. * Turn the Internet connectivity on or off by pressing the "Aeroplane mode" button. It opens the
  42. * status bar at the top, then drags it down to reveal the buttons on the 'Quick Settings' panel.
  43. */
  44. @Throws(UiObjectNotFoundException::class)
  45. private fun toggleAeroplaneModeButton() {
  46. try {
  47. airplaneModeOn = getCurrentAirplaneModeSetting()
  48. } catch (e: SecurityException) {
  49. e.printStackTrace()
  50. Assert.fail()
  51. } catch (e: IOException) {
  52. e.printStackTrace()
  53. Assert.fail()
  54. }
  55. // Open the status bar at the top; drag it down to reveal the buttons
  56. val device = UiDevice.getInstance(getInstrumentation())
  57. device.openQuickSettings()
  58. // Wait for the button to be visible, because opening the Quick Settings is animated.
  59. // You can use any string here; You only need a time delay wait here.
  60. val description = By.desc("AeroplaneMode")
  61. device.wait(Until.hasObject(description), 2000)
  62. // Search for and click the button
  63. var buttonClicked = clickObjectIfFound(device,
  64. "Aeroplane mode", "Airplane mode", "機内モード", "Modo avión")
  65. if (!buttonClicked) {
  66. // Swipe the Quick Panel window to the LEFT, if possible
  67. val screenWidth = device.displayWidth
  68. val screenHeight = device.displayHeight
  69. device.swipe((screenWidth * 0.80).toInt(), (screenHeight * 0.30).toInt(),
  70. (screenWidth * 0.20).toInt(), (screenHeight * 0.30).toInt(), 50)
  71. buttonClicked = clickObjectIfFound(device,
  72. "Aeroplane mode", "Airplane mode", "機内モード", "Modo avión")
  73. }
  74. if (!buttonClicked) {
  75. // Swipe the Quick Panel window to the RIGHT, if possible
  76. val screenWidth = device.displayWidth
  77. val screenHeight = device.displayHeight
  78. device.swipe((screenWidth * 0.20).toInt(), (screenHeight * 0.30).toInt(),
  79. (screenWidth * 0.80).toInt(), (screenHeight * 0.30).toInt(), 50)
  80. clickObjectIfFound(device,
  81. "Aeroplane mode", "Airplane mode", "機内モード", "Modo avión")
  82. }
  83. // Wait for the Internet to disconnect or re-connect
  84. device.wait(Until.hasObject(description), 6000)
  85. // Close the Quick Settings panel, using the guide from:
  86. // https://stackoverflow.com/questions/22634446/sending-intent-to-broadcastreceiver-from-adb
  87. UiDevice.getInstance(getInstrumentation()).executeShellCommand(
  88. "am broadcast -a android.intent.action.CLOSE_SYSTEM_DIALOGS")
  89. // Close the Quick Settings panel. This is the old way, which will give
  90. // a deprecation warning for using Intent.ACTION_CLOSE_SYSTEM_DIALOGS
  91. // getInstrumentation().context
  92. // .sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS))
  93. // Verify the change in the device settings
  94. try {
  95. airplaneModeOn = getCurrentAirplaneModeSetting()
  96. } catch (e: SecurityException) {
  97. e.printStackTrace()
  98. Assert.fail()
  99. } catch (e: IOException) {
  100. e.printStackTrace()
  101. Assert.fail()
  102. }
  103. }
  104. /**
  105. * On Android 8/9, use an 'adb shell' command to retrieve the "Airplane Mode" setting, like this:
  106. *
  107. *
  108. * `adb shell settings list global | grep airplane_mode_on ==> "airplane_mode_on=0"`
  109. *
  110. *
  111. * (But note that grep is not available on the Android shell. See guidance URLs below)
  112. *
  113. *
  114. * * https://www.reddit.com/r/tasker/comments/fbi5ai/psa_you_can_use_adb_to_find_all_the_settings_that/
  115. * * https://stackoverflow.com/questions/33970956/test-if-soft-keyboard-is-visible-using-espresso
  116. *
  117. *
  118. * On all other Android OS versions, use `Settings.System.getInt()` to retrieve the "Airplane Mode" setting.
  119. * It sets `airplaneModeOn = 1 (true)` or `airplaneModeOn = 0 (false)`
  120. *
  121. * @throws IOException if `executeShellCommand()` didn't work
  122. * @throws SecurityException if `Settings.System.getInt()` didn't work
  123. */
  124. @Throws(IOException::class, SecurityException::class)
  125. private fun getCurrentAirplaneModeSetting(): Int {
  126. if (Build.VERSION.SDK_INT in 26..28 /*Android 8-9*/) {
  127. val shellResponse = UiDevice
  128. .getInstance(getInstrumentation())
  129. .executeShellCommand("settings list global")
  130. airplaneModeOn = when {
  131. shellResponse.contains("airplane_mode_on=1") -> 1
  132. shellResponse.contains("airplane_mode_on=0") -> 0
  133. else -> throw IOException("Unsuitable response from adb shell command 'settings list global'")
  134. }
  135. } else {
  136. // Oddly this causes a SecurityException on Android 8,9 devices
  137. airplaneModeOn = Settings.System.getInt(
  138. getInstrumentation().context.contentResolver,
  139. Settings.Global.AIRPLANE_MODE_ON,
  140. 0)
  141. }
  142. return airplaneModeOn
  143. }
  144. /**
  145. * Make UiAutomator search for and click a single button, based on its text label.
  146. *
  147. * Sometimes multiple buttons will match the required text label. For example,
  148. * when Airplane mode is switched on, "Mobile data Aeroplane mode" and "Aeroplane mode"
  149. * are 2 separate buttons on the Quick Settings panel, on Android 10+.
  150. * For Aeroplane mode, always click on the last matched item.
  151. *
  152. * @param textLabels You must supply the language variants of the button that you want to click,
  153. * for example "Cancel" (English), "Cancelar" (Spanish), "취소" (Korean)
  154. * @return True if a button was found and clicked, otherwise return false
  155. */
  156. private fun clickObjectIfFound(device: UiDevice, vararg textLabels: String): Boolean {
  157. for (languageVariant in textLabels) {
  158. val availableButtons = device.findObjects(By.text(languageVariant))
  159. if (availableButtons.size >= 1) {
  160. if (airplaneModeButtonPosition == null) {
  161. availableButtons[availableButtons.size - 1].click()
  162. airplaneModeButtonPosition = availableButtons[availableButtons.size - 1].visibleCenter
  163. return true
  164. } else {
  165. // Use the stored position to avoid clicking on the wrong button
  166. for (button in availableButtons) {
  167. if (button.visibleCenter == airplaneModeButtonPosition) {
  168. button.click()
  169. airplaneModeButtonPosition = null
  170. return true
  171. }
  172. }
  173. }
  174. }
  175. }
  176. return false
  177. }
  178. @After
  179. fun cleanup() {
  180. // Switch the Internet connectivity back on, for other tests.
  181. if (airplaneModeOn == ON) {
  182. toggleAeroplaneModeButton()
  183. assertThat(airplaneModeOn, `is`(OFF))
  184. }
  185. }

如果您的设备使用的语言与英语不同,则必须调整字符串"Aeroplane mode"。例如,您可以在这里查看大约70种语言的翻译:https://github.com/aosp-mirror/platform_frameworks_base/search?q=global_actions_toggle_airplane_mode(截至2023年9月,您必须登录GitHub帐户才能查看搜索结果)。

展开查看全部
yacmzcpb

yacmzcpb7#

由于@user2511882的回答,您可以通过以下方式在Android X Test中使用Application context而不是Activity:

  1. internal fun switchWifi(value: Boolean) {
  2. val wifiManager = ApplicationProvider.getApplicationContext<YourApplicationClass>().getSystemService(Context.WIFI_SERVICE) as WifiManager
  3. wifiManager.isWifiEnabled = value}

考虑到这种方法仅适用于API <= 28。还有其他方法,如使用UI AutomatorAPI > 28

相关问题