Поиск элементов для нативных и гибридных приложений (Appium)
Есть множество способов найти элементы для нативных и гибридных приложений, такие как UIAutomatorviewer (для Android) и Appium Inspector. Начнем с первого.
Поиск элементов с UIAutomatorviewer
UIAutomatorviewer можно найти в папке Android SDK (C:\%android-sdk%\tools); на Mac можно найти в папке tools:
При открытии, вы увидите такой экран:
Рассмотрим пример со стандартным калькулятором Android:
Откройте эмулятор Android или реальное устройство.
Запустите калькулятор.
В окне UIAutomatorviewer, кликните на иконку скриншота девайса. Если запущено больше одного устройства, UIAutomatorviewer попросит вас выбрать девайс.
Теперь нужно найти элементы приложения, используя разные локаторы.
Поиск по ID
Сигнатура метода такая же, как поиск элемента по ID в web-приложении:
findElement(By.id(String id));
В метод передается ID элемента, с которым мы хотим работать. Ниже пример идентификации клавиши «5» в калькуляторе с использованием UI Automator Viewer:
Открыть UI Automator Viewer и нажать на клавишу «5» в приложении.
В разделе Node Details, вы получите resource-id вида com.android.calculator2:id/digit5:
Мы можем resource-id как ID, чтобы взаимодействовать с клавишей:
Чтобы получить значение элемента EditBox, используйте команду:
editBox.getText();
Если этот класс используется для нескольких элементов, мы можем обратиться к элементу по индексу в возвращаемой коллекции. Например, мы хотим обратится к клавише «7» по имени класса:
Мы использовали метод findElements вместо findElement; так мы получим больше одного элемента по селектору. В нашем примере, у клавиши «7» значение индекса — 1. Поэтому, мы обратились к 1му элементу.
Поиск по AccessibilityId
Разработчики Appium хотели дать нам больше возможностей для локализации элементов, поэтому они создали AccessibilityId. Этот локатор определяет элементы так же, как ID и name. Сигнатура метода:
findElement(By.AccessibilityId(String AccId));
Ниже пример взаимодействия к кнопкой "+":
Откройте UI Automator Viewer и кликните в калькуляторе на "+".
В разделе Node Details, вы найдете content-desc со значением «plus»:
В Node details мы можем выбрать любое поле. Например, resource-id со значением com.android.calculator2:id/equal. Мы можем использовать resource-id как UIAuto для работы с клавишей "=":
Чтобы узнать больше об этом локаторе, посетите эту и эту страницу.
Поиск элементов с Appium Inspector
В предыдущей главе мы уже узнали, что Appium Inspector хорошо работает на Mac. Работая на Mac, мы можем его использовать для поиска элементов. Чтобы запустить Appium Inspector для Android, нам нужно выполнить следующие шаги:
Нужно определить путь до приложения, пакета или имя активити в Appium GUI при работе с эмулятором. Если работаем с девайсом, достаточно имени пакета или активити.
Как определить имя пакета или активити, если приложение выполняется на девайсе? Можете установить на девайс APK Info из Play Store. Если у вас есть тестируемое приложение на компьютере, то Appium server автоматически подтянет все имена после указания пути к приложени.
В разделе General Settings, должна быть выбрана опция Prelaunch Application.
Если вы работаете с эмулятором, тогда должна быть выбрана опция Launch AVD в разделе Android Settings (предполагается, что эмулятор вы уже создали). Если же вы работаете с девайсом, он должен быть подключен и должен быть разрешен USB debugging.
Чтобы ввести текст в EditBox, используйте команду:
editBox.sendKeys("12");
Поиск по IosUIAutomation
UIAutomation — JavaScript библиотека, использующаяся для поиска элементов в Apple's Automation Instruments. Разработчики Appium дали нам похожий способ поиска элементов в Appium, используя IosUIAutomation:
Specifies the elements in the layout hierarchy for tests to target, filtered by properties such as text value, content-description, class name, and state information. You can also target an element by its location in a layout hierarchy.
Set the search criteria to match widgets that are checkable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match widgets that are currently checked (usually for checkboxes). Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match widgets that are clickable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must match exactly with the string in your input argument. Matching is case-sensitive.
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must contain the string in your input argument. Matching is case-insensitive.
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must match exactly with the string in your input argument.
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must start with the string in your input argument. Matching is case-insensitive.
Set the search criteria to match widgets that are enabled. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match widgets that are focusable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match widgets that have focus. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Adds a child UiSelector criteria to this selector which is used to start search from the parent widget. Use this selector to narrow the search scope to sibling widgets as well all child widgets under a parent.
Set the search criteria to match the widget by its node index in the layout hierarchy. The index value must be 0 or greater. Using the index can be unreliable and should only be used as a last resort for matching. Instead, consider using the instance(int) method.
Set the search criteria to match the widget by its instance number. The instance value must be 0 or greater, where the first instance is 0. For example, to simulate a user click on the third image that is enabled in a UI screen, you could specify a a search criteria where the instance is 2, the className(String) matches the image widget class, and enabled(boolean)is true. The code would look like this: new UiSelector().className("android.widget.ImageView") .enabled(true).instance(2);
Set the search criteria to match widgets that are long-clickable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match widgets that are scrollable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match widgets that are currently selected. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Set the search criteria to match the visible text displayed in a widget (for example, the text label to launch an app). The text for the element must match exactly with the string in your input argument. Matching is case-sensitive.
Set the search criteria to match the visible text in a widget where the visible text must contain the string in your input argument. The matching is case-sensitive.
Set the search criteria to match the visible text displayed in a layout element, using a regular expression. The text in the widget must match exactly with the string in your input argument.
Комментариев нет:
Отправить комментарий