Unit 3: Android Native Apps Automation with Appium - Subjective Questions
CSE379 — Mobile Automated Testing • Practice Questions with Detailed Answers
20 questions
Define ID, XPath, and Accessibility ID locators in Appium. Compare them based on syntax, reliability, and execution speed.
Appium locators identify UI elements in a mobile application.
- ID locator: Uses the Android resource ID assigned to an element. Example:
driver.findElement(AppiumBy.id("com.demo:id/loginButton")). It is generally fast, readable, and reliable when IDs are unique. - XPath locator: Uses the XML hierarchy of the application screen. Example:
driver.findElement(AppiumBy.xpath("//android.widget.Button[@text='Login']")). It is flexible but usually slower and more fragile when the UI hierarchy changes. - Accessibility ID locator: Uses the element's accessibility label, which normally maps to
content-descon Android. Example:driver.findElement(AppiumBy.accessibilityId("Login")). It is fast, readable, and promotes accessible application design.
Preferred order:
- Accessibility ID or ID when unique and stable.
- Android UIAutomator for Android-specific searches.
- XPath only when more stable alternatives are unavailable.
A good locator should be unique, stable, readable, and independent of screen position.
Explain how an Android element can be located and clicked using its resource ID. Give an Appium example and mention important precautions.
An Android resource ID uniquely identifies a view in the application layout. In Appium, it can be used through AppiumBy.id.
Example:
WebElement countryField = driver.findElement(
AppiumBy.id("com.shoppingapp:id/country")
);
countryField.click();
The fully qualified ID generally follows the format package_name:id/resource_name.
Precautions:
- Verify the ID using Appium Inspector or Android UI hierarchy tools.
- Ensure that the ID is unique on the current screen.
- Do not confuse the visible text of an element with its resource ID.
- Use an explicit wait before interacting with elements loaded asynchronously.
- Avoid IDs generated dynamically at runtime unless a stable portion can be identified through another strategy.
ID locators are preferred because they are usually faster and less dependent on the structure of the UI than XPath.
Distinguish between absolute XPath and relative XPath in Android automation. Why should relative XPath normally be preferred?
Absolute XPath starts from the root of the Android UI hierarchy and includes every level leading to the target element. For example:
/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.Button
Relative XPath searches for an element using selected attributes or relationships. For example:
//android.widget.Button[@text='Add to Cart']
Comparison:
- Absolute XPath is long and tightly coupled to the complete screen hierarchy.
- Relative XPath is shorter and can use attributes such as
text,resource-id,content-desc, andclass. - A small layout change can easily break an absolute XPath.
- A carefully designed relative XPath is more maintainable.
Relative XPath should normally be preferred because it focuses on stable element properties rather than the complete hierarchy. However, XPath should still be a fallback because XML traversal may be slower than ID or Accessibility ID lookup.
What is an Accessibility ID in Appium? Explain its relationship with Android's content-desc attribute and state its advantages.
An Accessibility ID is a cross-platform Appium locator that identifies an element by its accessibility label. On Android, it commonly corresponds to the content-desc attribute.
Example:
WebElement cart = driver.findElement(
AppiumBy.accessibilityId("Cart")
);
cart.click();
Advantages:
- It is generally faster than XPath.
- It produces short and readable test code.
- It is less dependent on the element's position in the UI hierarchy.
- It encourages developers to create interfaces that can be understood by accessibility services.
- The same conceptual locator strategy can be used on Android and iOS, although the underlying platform attributes differ.
The accessibility label should be meaningful and unique. If multiple elements have the same content-desc, findElement may return only the first match, so the application should ideally assign distinct labels.
Describe how Appium returns a list of matching elements on an Android screen. How does findElements differ from findElement?
findElements returns a list containing all elements that match a locator.
Example:
List<WebElement> products = driver.findElements(
AppiumBy.id("com.shoppingapp:id/productName")
);
for (WebElement product : products) {
System.out.println(product.getText());
}
Difference:
findElementreturns the first matching element.findElementthrowsNoSuchElementExceptionif no match is found.findElementsreturnsList<WebElement>.findElementsusually returns an empty list if no elements match.
A test can verify the number of results with products.size() and check emptiness with products.isEmpty(). For dynamic screens, an explicit wait should be used before retrieving the list so that the application has enough time to render the expected elements.
Explain how mobile pop-ups, Android permission dialogs, and application alerts can be handled in Appium.
The handling method depends on the type of pop-up.
-
Android runtime permissions: Permissions may be granted automatically by setting the
autoGrantPermissionscapability totrue. They can also be handled by locating buttons such ascom.android.permissioncontroller:id/permission_allow_button. -
Native application alerts: Appium's alert API can be used:
Alert alert = driver.switchTo().alert();
String message = alert.getText();
alert.accept(); -
Custom application pop-ups: These are normal UI elements and should be handled using ID, Accessibility ID, or another suitable locator.
-
Optional pop-ups: Use
findElementsand check whether the returned list is empty before clicking. This avoids an exception when the pop-up does not appear.
A robust test should wait for the pop-up, verify its message when relevant, and choose the correct action such as Allow, Deny, Accept, or Cancel. Hard-coded delays should be avoided.
How can text be extracted from an Android element and information be entered into input fields using Appium?
Text can normally be extracted with getText(). Depending on the widget, it may also be obtained from attributes such as text, content-desc, or value.
Example:
WebElement heading = driver.findElement(
AppiumBy.id("com.shoppingapp:id/title")
);
String actualHeading = heading.getText();
WebElement nameField = driver.findElement(
AppiumBy.id("com.shoppingapp:id/nameField")
);
nameField.click();
nameField.clear();
nameField.sendKeys("Anita Sharma");
driver.hideKeyboard();
Good practices:
- Wait until the element is visible or editable.
- Call
clear()when an existing value must be removed. - Hide the keyboard if it covers the next control.
- Assert the extracted text after trimming unnecessary spaces.
- Do not log confidential values such as passwords.
If getText() returns an empty value, inspect the element to determine whether the required content is stored in another attribute.
Describe the application features and test cases that should be identified before automating a mobile shopping application.
Before implementation, the tester should study the application's workflows, screen transitions, data requirements, and expected results.
Important features may include:
- User registration and login.
- Country or preference selection.
- Product listing, search, filtering, and scrolling.
- Product detail and add-to-cart operations.
- Cart quantity, price, and total calculation.
- Checkout form validation.
- Toast messages, alerts, and permission dialogs.
Representative test cases:
- Submit a form with valid and invalid data.
- Leave mandatory fields blank and verify validation messages.
- Select a product dynamically by its displayed name.
- Add multiple products and verify cart contents.
- Compare the displayed total with the sum of product prices.
- Verify behavior under slow loading or interrupted navigation.
Each test case should specify preconditions, test data, execution steps, expected results, and cleanup. Tests should also be independent and repeatable.
Design an Appium test case for filling and submitting customer details in a mobile shopping application.
Test objective: Verify that valid customer information can be entered and submitted successfully.
Preconditions:
- The application is installed and launched.
- The user is on the shopping form screen.
- Required permissions have been handled.
Steps:
- Locate the name field by ID.
- Clear it and enter a valid customer name.
- Select the required gender option.
- Open the country list.
- Scroll to and select the required country.
- Hide the keyboard if it blocks controls.
- Tap the Let's Shop or submit button.
- Wait for the product screen.
Example operations:
driver.findElement(AppiumBy.id("com.app:id/nameField"))
.sendKeys("Ravi Kumar");
driver.findElement(AppiumBy.id("com.app:id/radioMale")).click();
driver.findElement(AppiumBy.id("com.app:id/countrySpinner")).click();
driver.findElement(AppiumBy.androidUIAutomator(
"new UiScrollable(new UiSelector().scrollable(true))" +
".scrollIntoView(new UiSelector().text(\"India\"))"
)).click();
driver.findElement(AppiumBy.id("com.app:id/btnShop")).click();
Expected result: The form is accepted and the product list is displayed.
What is an Android toast message? Explain how an error-validation toast can be verified using Appium.
A toast is a short-lived Android notification that displays feedback without requiring user interaction. For example, submitting a shopping form without entering a name may display Please enter your name.
A common Appium approach is to locate the toast by XPath using the android.widget.Toast class:
WebElement toast = new WebDriverWait(driver, Duration.ofSeconds(5))
.until(ExpectedConditions.presenceOfElementLocated(
AppiumBy.xpath("//android.widget.Toast")
));
String actualMessage = toast.getText();
Assertions.assertEquals("Please enter your name", actualMessage);
A more specific locator may use:
//android.widget.Toast[@text='Please enter your name']
Because a toast disappears quickly, the test should begin waiting immediately after the action that triggers it. The exact behavior can depend on the Android version, automation backend, and application implementation.
Discuss the challenges involved in validating toast messages and suggest techniques for making toast-validation tests reliable.
Toast validation is challenging because a toast is temporary and may disappear before Appium inspects it.
Common challenges:
- Very short display duration.
- Differences among Android versions and device vendors.
- Delayed test execution after the triggering action.
- Toast text being unavailable through ordinary element methods in some environments.
- Incorrect matching caused by spaces, capitalization, or localization.
Reliability techniques:
- Start an explicit wait immediately after triggering the validation.
- Use a direct locator such as
//android.widget.Toastor an exact text condition. - Keep the wait short but sufficient for the application's response time.
- Run the test with a compatible UiAutomator2 driver and Appium version.
- Capture screenshots and page sources on failure for diagnosis.
- Confirm that the message is truly a native toast; some applications imitate toasts with custom views.
- Avoid fixed calls such as
Thread.sleep, which can either waste time or miss the toast.
When possible, developers may expose validation through a persistent and accessible UI element, making the test more stable.
Explain how UiScrollable and UiSelector can be used to scroll through an Android product list in Appium.
UiScrollable is an Android UIAutomator class that operates on a scrollable container, while UiSelector identifies the container or target element.
Example:
WebElement product = driver.findElement(
AppiumBy.androidUIAutomator(
"new UiScrollable(new UiSelector().scrollable(true))" +
".scrollIntoView(new UiSelector().text(\"Air Jordan 4 Retro\"))"
)
);
product.click();
Process:
new UiSelector().scrollable(true)identifies a scrollable container.UiScrollableperforms the scrolling operation.scrollIntoViewcontinues scrolling until the target selector is visible.- The returned element can then be clicked or inspected.
This approach is useful for Android native applications because the framework performs the search and scroll together. If several containers are scrollable, a resource ID or instance number should be used to identify the intended container more precisely.
Describe how a swipe-based scroll can be implemented with Appium's W3C Actions API. Compare it with text-based UiScrollable scrolling.
A swipe can be created as a W3C pointer action using screen coordinates.
Conceptual sequence:
- Create a virtual finger pointer.
- Move it to a point near the lower part of the screen.
- Press down.
- Move upward over a defined duration.
-
Release the pointer.
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence swipe = new Sequence(finger, 1);
swipe.addAction(finger.createPointerMove(
Duration.ZERO, PointerInput.Origin.viewport(), 500, 1500));
swipe.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));
swipe.addAction(finger.createPointerMove(
Duration.ofMillis(700), PointerInput.Origin.viewport(), 500, 500));
swipe.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(List.of(swipe));
Comparison:
UiScrollableis convenient when the target text or another selector is known.- W3C Actions support custom direction, distance, and gesture behavior.
- Fixed coordinates may fail on devices with different resolutions.
- Coordinate calculations based on screen size are more portable than hard-coded values.
- Swipe loops require a termination condition to prevent infinite scrolling.
Develop an approach for dynamically selecting a product by scanning the visible product list based on its text.
The test should not assume a fixed product position. It should inspect product cards, compare their names with the required name, and click the matching card's action button.
Algorithm:
- Retrieve all visible product cards with
findElements. - Extract the name from each card.
- Compare it with the target using
equalsIgnoreCaseor another suitable rule. - Click the Add to Cart button inside the matching card.
- If no match is visible, scroll and repeat.
- Stop when the product is found or when the end of the list is reached.
Example for visible cards:
for (WebElement card : driver.findElements(
AppiumBy.id("com.app:id/productCard"))) {
String name = card.findElement(
AppiumBy.id("com.app:id/productName")).getText().trim();
if (name.equalsIgnoreCase(targetProduct)) {
card.findElement(
AppiumBy.id("com.app:id/addToCart")).click();
found = true;
break;
}
}
Locating the button relative to its product card avoids accidentally selecting another product's button.
How can a product-scanning test determine that it has reached the end of a dynamically loaded list and avoid an infinite scroll loop?
A scanning test must use a clear termination rule.
Possible techniques:
- Set a maximum number of scroll attempts.
- Record the text of the last visible product before each swipe. If it remains unchanged after a swipe, the end may have been reached.
- Compare the current page source or visible product names with those from the previous iteration.
- Detect a visible footer or an explicit
End of listelement. - Check whether the swipe operation caused any change in element coordinates or list content.
Suggested logic:
- Scan all currently visible products.
- Return immediately if the target is found.
- Save the final visible product's name.
- Scroll once and wait for the list to stabilize.
- Read the new final product name.
- Stop if the name is unchanged or if the maximum attempt count is reached.
- Fail with a meaningful assertion if the target was not found.
This protects the test from endless execution and produces a useful failure message such as Requested product was not present in the list.
Derive the logic for validating the total amount displayed in a shopping cart when multiple product prices are shown.
Assume that the cart contains products and their numeric prices are . The expected total is:
Validation procedure:
- Retrieve all product price elements.
- Extract each displayed string, such as
$120.50. - Remove currency symbols, separators, and spaces.
- Convert each value to
BigDecimalto reduce floating-point errors. - Add all values.
- Extract and convert the displayed total in the same way.
- Compare the calculated and displayed totals.
Illustrative code:
BigDecimal expected = BigDecimal.ZERO;
for (WebElement price : priceElements) {
String value = price.getText().replaceAll("[^0-9.]", "");
expected = expected.add(new BigDecimal(value));
}
String totalText = totalElement.getText()
.replaceAll("[^0-9.]", "");
BigDecimal actual = new BigDecimal(totalText);
Assertions.assertEquals(0, expected.compareTo(actual));
For locale-sensitive prices, a locale-aware number parser should be used instead of assuming that a period is always the decimal separator.
Design a complete test case for validating cart contents and the total amount after adding products dynamically.
Objective: Confirm that selected products appear in the cart and that the displayed total equals the sum of their prices.
Preconditions: The user has completed the shopping form and the product list is visible.
Steps:
- Store the required product names in a list.
- For each name, scan or scroll through the product list.
- Add the matching product to the cart.
- Verify that the cart count is updated.
- Open the cart.
- Retrieve all cart product names and verify that every requested product is present.
- Retrieve all individual prices.
- Convert the prices to numeric values and calculate their sum.
- Extract the displayed total.
- Assert that calculated and displayed totals are equal.
Expected result:
- No unwanted product is added.
- Each selected product appears once unless duplicates are intended.
- The cart count matches the number of added products.
- The displayed total satisfies .
The test should fail with descriptive messages identifying missing products or the expected and actual totals.
Explain how user-defined functions can optimize Appium test code. Provide examples of reusable functions for shopping-app automation.
User-defined functions place repeated operations in reusable methods. This reduces duplication and improves readability, maintainability, and error handling.
Useful functions include:
waitAndClick(By locator)enterText(By locator, String value)scrollToText(String text)selectProduct(String productName)parsePrice(String displayedPrice)calculateCartTotal()isElementPresent(By locator)
Example:
public void enterText(By locator, String value) {
WebElement field = wait.until(
ExpectedConditions.visibilityOfElementLocated(locator));
field.clear();
field.sendKeys(value);
}
public BigDecimal parsePrice(String text) {
String numeric = text.replaceAll("[^0-9.]", "");
return new BigDecimal(numeric);
}
Functions should represent meaningful operations and should not hide important assertions. Locators may be organized using the Page Object Model so that page behavior and element definitions are separated from test scenarios.
Why are explicit waits important in Android native-app automation? Explain how waits improve tests involving lists, pop-ups, forms, and scrolling.
Mobile applications often load data asynchronously, animate screens, or wait for network responses. Attempting an operation before an element is ready can cause intermittent failures.
An explicit wait pauses until a specific condition is satisfied:
WebElement button = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(
AppiumBy.id("com.app:id/submit")));
button.click();
Applications of waits:
- Wait for a form field to become visible before entering text.
- Wait for a product list to contain elements before scanning it.
- Wait for a pop-up or toast immediately after its triggering action.
- Wait for an element to become clickable after scrolling.
- Wait for a destination screen to confirm successful navigation.
Explicit waits are better than fixed sleeps because they continue as soon as the condition is met. Tests should use conditions that reflect the expected application state and avoid mixing excessively long implicit and explicit waits.
Propose a maintainable automation framework structure for testing an Android shopping application with Appium.
A maintainable framework should separate driver management, page behavior, test data, assertions, and reporting.
Suggested structure:
- Driver factory: Creates and closes the
AndroidDriverand manages capabilities. - Base test: Performs common setup and teardown.
- Page objects: Represent screens such as
FormPage,ProductPage, andCartPage. - Utility classes: Provide waits, scrolling, gestures, screenshots, price parsing, and configuration reading.
- Test classes: Describe scenarios and assertions without low-level locator details.
- Data layer: Stores user details, product names, and environment configuration.
- Reporting layer: Records steps, screenshots, device information, and failures.
Example page-level methods:
formPage.fillCustomerDetails(data)productPage.addProductByName(name)cartPage.getCalculatedTotal()cartPage.getDisplayedTotal()
Locators should be centralized, functions should have single responsibilities, and teardown should run even after a failure. This design minimizes the changes required when the application UI is updated.
Define ID, XPath, and Accessibility ID locators in Appium. Compare them based on syntax, reliability, and execution speed.
Appium locators identify UI elements in a mobile application.
- ID locator: Uses the Android resource ID assigned to an element. Example:
driver.findElement(AppiumBy.id("com.demo:id/loginButton")). It is generally fast, readable, and reliable when IDs are unique. - XPath locator: Uses the XML hierarchy of the application screen. Example:
driver.findElement(AppiumBy.xpath("//android.widget.Button[@text='Login']")). It is flexible but usually slower and more fragile when the UI hierarchy changes. - Accessibility ID locator: Uses the element's accessibility label, which normally maps to
content-descon Android. Example:driver.findElement(AppiumBy.accessibilityId("Login")). It is fast, readable, and promotes accessible application design.
Preferred order:
- Accessibility ID or ID when unique and stable.
- Android UIAutomator for Android-specific searches.
- XPath only when more stable alternatives are unavailable.
A good locator should be unique, stable, readable, and independent of screen position.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →