Thursday, December 5, 2013

How can we handle Toggle Switch in UiAutomator?

Let us see how we can handle toggle buttons in UiAutomator. I am taking an example of toggle Wi-Fi buttons from settings page.

Test steps:
1. Launch settings application from the App tray
2. Go to Wi-Fi Settings and toggle the wi-fi settings

Test Procedure:

Step 1: Follow this post on how to launch settings application from App tray

Step 2: Toggle wi-fi settings

Before accessing the wi-fi settings, let us write small code to check if the settings application is already launched. Because the UiAutomatorTestCase class extends junit.framework.TestCase, we can use the JUnit Assert class to test that UI components in the app return the expected results

    // Validate that the package name is the expected one
      UiObject settingsValidation = new UiObject(new UiSelector()
         .packageName("com.android.settings"));
      assertTrue("Unable to detect Settings", 
         settingsValidation.exists()); 

Now, let us get the properties of Wi-Fi settings from UiAutomatorViewer

From the above Screnshot, we can get the properties of Wi-Fi settings,
  • Index = 1
  • class = android.widget.LinearLayout
  • scrollable = false
Using these properties, we can create UiObject for Wi-Fi settings. it is also clear that "Switch: ON" and "TextView: Wi-Fi" are child objects of the LinearLayout.
 

UiObject WiFiSettings = new UiObject(new UiSelector().className("android.widget.LinearLayout") .scrollable(false).index(1));
if(WiFiSettings.exists())              WiFiSettings.click();

Now, let us create child object for "Switch: ON"

UiObject WifiOnButton = WiFiSettings.getChild(new UiSelector().text("ON"));

if (WifiOnButton.exists()){              WifiOnButton.click();



If the Wi-Fi is already turned off, we can get the properties of "Switch:OFF"

 
UiObject WifiOffButton = WiFiSettings.getChild(new UiSelector().text("OFF"));
if (WifiOffButton.exists())
 WifiOffButton.click();
Here is the complete code
 public void testToggleWiFiSettings() throws RemoteException,
   UiObjectNotFoundException {

  // Validate that the package name is the expected one
  UiObject settingsValidation = new UiObject(
    new UiSelector().packageName("com.android.settings"));
  assertTrue("Unable to detect Settings", settingsValidation.exists());

  // Wi-Fi settings
  UiObject WiFiSettings = new UiObject(new UiSelector()
    .className("android.widget.LinearLayout").scrollable(false)
    .index(1));

  if (WiFiSettings.exists())
   WiFiSettings.click();

  // Switch ON
  UiObject WifiOnButton = WiFiSettings.getChild(new UiSelector()
    .text("ON"));
  // Switch OFF
  UiObject WifiOffButton = WiFiSettings.getChild(new UiSelector()
    .text("OFF"));

  if (WifiOnButton.exists()) {
   WifiOnButton.click();
  } else if (WifiOffButton.exists()) {
   WifiOffButton.click();
  }

 }