UI Selector and Scrolling Actions - Notes By ShariqSP
Understanding UI Selector and Scrolling Actions in Android Testing
UI Selector Class - Locate Element
The UiSelector
class in Android's UiAutomator
framework is used to locate user interface elements in Android applications during automated testing. It provides a fluent API for specifying search criteria, enabling precise identification of elements based on various properties such as text, resource ID, class name, description, and more.
Usage Example
Here is an example of using UiSelector
to locate elements:
// Import necessary classes
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.UiObject;
// Locate an element by text
UiObject element = device.findObject(new UiSelector().text("Example Text"));
// Locate an element by resource ID
UiObject elementById = device.findObject(new UiSelector().resourceId("com.example:id/button"));
The UiSelector
class offers a variety of methods like className()
, description()
, index()
, and enabled()
for flexible and detailed searches.
UI Scrollable Horizontally or Vertically for Swiping
The UiScrollable
class in UiAutomator
is used to handle scrolling actions in a UI. It supports both horizontal and vertical scrolling, making it possible to interact with lists, grids, or pages that require swiping.
Vertical Scrolling Example
// Create a UiScrollable object for a vertically scrollable view
UiScrollable scrollable = new UiScrollable(new UiSelector().scrollable(true));
// Scroll forward
scrollable.scrollForward();
// Scroll backward
scrollable.scrollBackward();
Horizontal Scrolling Example
// Set the scrollable direction to horizontal
scrollable.setAsHorizontalList();
// Scroll forward
scrollable.scrollForward();
// Scroll backward
scrollable.scrollBackward();
The UiScrollable
class also provides methods like scrollIntoView()
to scroll until a specific element becomes visible.
Fling Backward or Forward to the Beginning
In addition to precise scrolling, UiScrollable
supports fling gestures for quick navigation to the start or end of a scrollable view. Fling gestures are faster than scrolling and typically cover more distance in one motion.
Example of Flinging
// Fling forward to the end
scrollable.flingForward();
// Fling backward to the beginning
scrollable.flingBackward();
Fling gestures are useful for rapidly navigating through long lists or grids where specific items are not immediately visible.
Best Practices
- Ensure that the
scrollable
property is set correctly for the target view. - Use
UiSelector
methods to locate unique and identifiable elements for reliability. - Combine scrolling and locating elements to interact with items in dynamic or large UIs effectively.
The combination of UiSelector
and UiScrollable
provides robust tools for automated testing of complex Android UIs.