How to Automate Wishlists Testing (Step-by-Step)
Automating wishlists testing is crucial for ensuring a seamless and reliable shopping experience for users across web and mobile applications. This step-by-step guide will walk you through the entire
How to Automate Wishlists Testing (Step-by-Step)
Automating wishlists testing is crucial for ensuring a seamless and reliable shopping experience for users across web and mobile applications. This step-by-step guide will walk you through the entire process, from understanding the value of automation for wishlists to implementing robust testing strategies and integrating them into your CI/CD pipeline. By following these guidelines, you can significantly improve the quality and stability of your wishlist features, reducing bugs, enhancing user satisfaction, and freeing up valuable testing resources.
Wishlists are a core feature in e-commerce platforms, allowing users to save items for later purchase. Robust testing of this functionality is paramount. This includes verifying that items can be added and removed, that quantities are handled correctly, that multiple wishlists are supported if applicable, and that the data persists across sessions and devices. When done effectively, automated wishlists testing not only catches regressions but also validates complex user flows that might be missed during manual testing. This guide will cover the essential considerations, from selecting the right tools to mastering advanced techniques for stable and efficient automated tests.
The Value Proposition of Automating Wishlists Testing
Before diving into the "how," it's essential to understand *why* you should invest in automating wishlists testing. Manual testing, while useful for exploratory testing and initial validation, becomes a bottleneck as applications grow and features evolve. Wishlist functionality, in particular, has several aspects that lend themselves well to automation:
- Repetitive Actions: Adding, removing, and checking items in a wishlist involves repetitive user interactions.
- Data Variations: Testing with different user accounts, varying numbers of items, and diverse product types can be tedious manually.
- Cross-Browser/Device Testing: Ensuring wishlists function correctly across multiple browsers, operating systems, and device form factors is time-consuming.
- Regression Testing: As new features are added or existing ones are modified, it's critical to ensure the wishlist functionality remains intact. Manual regression testing of wishlists can easily miss subtle bugs.
- Performance and Load: Simulating multiple users interacting with wishlists concurrently is impractical for manual testers.
Automated wishlists testing offers significant benefits:
- Increased Efficiency: Automated tests run much faster than manual tests, allowing for more frequent execution.
- Improved Accuracy and Consistency: Machines perform tasks precisely as programmed, eliminating human error.
- Early Bug Detection: Running automated tests frequently, especially in a CI/CD pipeline, catches bugs earlier in the development cycle when they are cheaper to fix.
- Broader Test Coverage: Automation enables testing a wider range of scenarios, including edge cases and negative test cases, that might be overlooked manually.
- Reduced Costs: While there's an initial investment in setting up automation, it leads to long-term cost savings by reducing manual effort and preventing costly production defects.
- Developer Confidence: Passing automated tests provides developers with confidence that their changes haven't broken core functionality.
When Automation Truly Pays Off for Wishlists
Not every feature requires immediate automation. For wishlists, automation becomes highly valuable when:
- The feature is stable and well-defined: Core wishlist functionality (add, remove, view) should be reasonably stable before heavy automation investment.
- The feature is critical to user conversion: Wishlists directly impact purchasing decisions, making their reliability crucial.
- The application is undergoing frequent changes: Agile development and continuous deployment necessitate rapid feedback loops, which automation provides.
- You need to test across multiple platforms/browsers: Ensuring consistent behavior across various environments is a prime use case for automation.
- You have a dedicated QA or development team that can maintain the tests: Automated tests are living artifacts that require ongoing maintenance.
Designing Your Wishlists Test Strategy
A well-defined test strategy is the foundation of successful automation. For wishlists, this involves identifying key functionalities, potential failure points, and the scope of your testing efforts.
Defining Core Wishlist Functionality to Test
The wishlist feature typically encompasses several distinct user interactions. A comprehensive test strategy should cover these:
- Adding Items:
- Add a single item to an empty wishlist.
- Add multiple items to an empty wishlist.
- Add an item that's already in the wishlist.
- Add an item from a product listing page.
- Add an item from a product detail page.
- Add an item with different variations (size, color).
- Add an item that becomes unavailable or is removed from the catalog.
- Viewing Wishlist:
- Verify all added items are displayed correctly.
- Check item details (name, image, price, variations).
- Ensure the correct number of items is shown.
- Verify pagination if the wishlist can become very large.
- Removing Items:
- Remove a single item from the wishlist.
- Remove multiple items from the wishlist.
- Remove the last item from the wishlist.
- Attempt to remove an item that's no longer available.
- Item Quantity and State:
- Verify quantity is handled correctly (typically one instance per item, or ability to add multiples).
- Check if an item in the wishlist is still in stock or out of stock.
- Test moving an item from the wishlist to the cart.
- Persistence:
- Ensure items remain in the wishlist after logging out and logging back in.
- Verify wishlist content persists across different devices for the same logged-in user.
- Test anonymous user wishlists (if supported) and their persistence (e.g., via cookies).
- Multiple Wishlists (if applicable):
- Create, name, and delete multiple wishlists.
- Add items to specific wishlists.
- Move items between wishlists.
- Set a default wishlist.
- Edge Cases and Negative Scenarios:
- Add a very large number of items to the wishlist.
- Add items with special characters in their names or details.
- Test with concurrent operations (e.g., adding and removing simultaneously).
- What happens if the user's session expires while they are managing their wishlist?
- Test adding/removing from a wishlist with an extremely long name.
Creating a Wishlists Test Matrix
A test matrix helps visualize the scope of your testing. It maps features against different environments or test types. For wishlists, this matrix can be quite detailed.
Example Wishlists Test Matrix
| Feature | Test Type | Description | Platform/Environment | Expected Outcome | Status (Manual/Auto) |
|---|---|---|---|---|---|
| Add Item to Wishlist | Functional | User adds a product from PDP to an empty wishlist. | Web (Chrome) | Item appears in wishlist with correct details. Wishlist count increments. | Auto |
| Add Item to Wishlist | Functional | User adds a product from PLP to an empty wishlist. | Web (Firefox) | Item appears in wishlist with correct details. Wishlist count increments. | Auto |
| Add Item to Wishlist | Functional | User adds an item with variations (size, color). | Web (Safari) | Item appears in wishlist with selected variations. | Auto |
| Add Item to Wishlist | Negative | User attempts to add an out-of-stock item. | Web (Chrome) | Add button might be disabled, or an error message is displayed. Item is not added. | Auto |
| View Wishlist | Functional | Verify display of multiple items, including images, titles, prices, and selected variations. | Web (All Browsers) | All items are displayed accurately. | Auto |
| View Wishlist | Functional | Verify wishlist count updates correctly after adding/removing items. | Web (All Browsers) | Count accurately reflects the number of items. | Auto |
| Remove Item | Functional | User removes a single item from a populated wishlist. | Web (Chrome) | Item is removed. Wishlist count decrements. | Auto |
| Remove Item | Functional | User removes all items from a wishlist. | Web (Chrome) | Wishlist becomes empty. "No items in wishlist" message is displayed. | Auto |
| Persistence (Logged In) | Functional | User logs in, adds items, logs out, logs back in. | Web (Chrome) | Items added previously are still present in the wishlist. | Auto |
| Persistence (Anonymous) | Functional | User browses as anonymous, adds item, closes tab, reopens. | Web (Chrome) | Item remains in wishlist (if cookie-based persistence is implemented). | Auto |
| Move to Cart | Functional | User moves an item from wishlist to cart. | Web (Chrome) | Item is removed from wishlist and appears in cart. | Auto |
| Multiple Wishlists | Functional | User creates a second wishlist, adds items to it. | Web (Chrome) | Second wishlist exists with correct items. | Auto |
| Multiple Wishlists | Functional | User moves an item from Wishlist A to Wishlist B. | Web (Chrome) | Item is removed from A and appears in B. | Auto |
| Accessibility | Accessibility | Check if "Add to Wishlist" buttons are keyboard navigable and have ARIA labels. | Web (Chrome) | Elements are focusable, have appropriate labels. | Auto (SUSA) |
| Security | Security | Test for unauthorized access to another user's wishlist (e.g., via URL manipulation). | Web (Chrome) | Access denied. User sees their own wishlist or an error. | Manual / Pen-Test |
| Performance | Load/Stress | Simulate 100 concurrent users adding to wishlists. | Web (LoadRunner) | Response times remain within acceptable limits. No errors. | Auto (Perf Tools) |
| Mobile App | Functional (iOS) | Add/remove items from wishlist on an iOS device. | iOS (iPhone) | Wishlist correctly updated. | Auto |
| Mobile App | Functional (Android) | Add/remove items from wishlist on an Android device. | Android (Pixel) | Wishlist correctly updated. | Auto |
Choosing the Right Automation Framework
The choice of framework significantly impacts your ability to build, maintain, and scale your automated wishlists tests. Consider the following factors:
- Application Type: Web, mobile native, hybrid, desktop.
- Technology Stack: Programming languages supported, integration with your existing tech stack.
- Learning Curve: How easy is it for your team to learn and become proficient?
- Community Support & Documentation: Active communities and good documentation are invaluable.
- Features: Reporting, parallel execution, cross-browser/device support, CI/CD integration.
- Cost: Open-source vs. commercial.
Popular Frameworks for Web Wishlists Testing
For web applications, several robust frameworks are available:
- Selenium WebDriver: The industry standard for browser automation. Supports multiple languages (Java, Python, C#, JavaScript). Offers extensive control but can be verbose and requires careful test design to be stable.
- Cypress: A modern, JavaScript-based framework that runs directly in the browser. Known for its speed, reliability, and developer-friendly features like time-travel debugging. Excellent for front-end testing.
- Playwright: Developed by Microsoft, Playwright supports multiple browsers (Chromium, Firefox, WebKit) and languages (JavaScript/TypeScript, Python, Java, .NET). It's known for its speed, robustness, and advanced features like auto-waits and network interception.
- Robot Framework: A generic test automation framework that supports keyword-driven testing. It can be extended with libraries like SeleniumLibrary to automate web UIs. Good for teams that prefer a keyword-driven approach.
Popular Frameworks for Mobile Wishlists Testing
For native or hybrid mobile applications:
- Appium: An open-source tool for automating native, hybrid, and mobile web applications on iOS and Android. It uses the WebDriver protocol, making it familiar to Selenium users.
- Espresso (Android): Google's native testing framework for Android. It's fast and reliable for Android UI tests.
- XCUITest (iOS): Apple's native testing framework for iOS. Offers robust UI testing capabilities for the Apple ecosystem.
Autonomous Exploration: A Script-Less Approach
While manual script creation is common, it's time-consuming and prone to becoming outdated. Autonomous QA platforms, like SUSATest, offer a different approach, particularly valuable for bootstrapping and augmenting traditional automation. These platforms explore your application automatically, interacting with elements like any real user would.
How Autonomous Exploration Helps Wishlists Testing:
- Initial Discovery: An autonomous agent can explore your e-commerce site, identify the "Add to Wishlist" buttons, discover the wishlist page, and perform basic add/remove operations without any pre-written scripts.
- Flow Identification: It can automatically identify and track key user flows, such as "Add to Wishlist -> View Wishlist -> Move to Cart."
- Bug Detection: During exploration, it can find crashes, ANRs (Application Not Responding errors), dead buttons, and UI glitches that might disrupt wishlist functionality.
- Accessibility & Security Checks: Platforms like SUSA can also identify WCAG accessibility violations and basic security vulnerabilities in the wishlist feature during their automated exploration.
- Regression Script Generation: Crucially, after its exploration, an autonomous platform can auto-generate regression scripts in formats like Appium (for mobile) or Playwright (for web). This dramatically reduces the initial effort required to build a stable automated test suite for your wishlists. You get a foundational set of tests without writing a single locator or wait statement initially.
Example: You can point SUSATest at your web application URL. It will start crawling, discover product pages, find "Add to Wishlist" buttons, add items, navigate to the wishlist page, and verify the items. It will then generate Playwright or Appium scripts based on the flows it discovered and the issues it found. This bootstraps your automation effort significantly.
Framework Comparison Table
| Feature | Selenium WebDriver | Cypress | Playwright | Appium | SUSATest (Autonomous) |
|---|---|---|---|---|---|
| Primary Use | Web | Web | Web | Mobile (Native/Hybrid/Web) & Desktop | Web & Mobile Native |
| Language Support | Java, Python, C#, JS, Ruby | JS/TS | JS/TS, Python, Java, .NET | JS/TS, Python, Java, Ruby, C# | N/A (Platform UI) |
| Execution | Remote via WebDriver | In-browser | Local/Remote | Remote via WebDriver | Cloud / Local Agent |
| Speed | Moderate | Fast | Very Fast | Moderate | Varies (Discovery vs. Execution) |
| Reliability | Moderate (requires careful handling) | High | High | Moderate | High (for discovered flows) |
| Flakiness | High (if not managed) | Low | Low | Moderate | Low (for generated scripts) |
| Auto-Waits | No (manual needed) | Yes | Yes | No (manual needed) | Yes (for generated scripts) |
| Cross-Browser | High | Limited (Chrome, Firefox, Edge) | Very High | High (via simulators/devices) | High (Web), High (Mobile) |
| Script Generation | No | No | No | No | Yes (Appium, Playwright) |
| Initial Setup Effort | Moderate to High | Low to Moderate | Moderate | Moderate to High | Low (for discovery) |
| Maintenance | High | Moderate | Moderate | High | Low (for generated scripts) |
Writing Stable and Maintainable Wishlists Tests
Flaky tests are a bane of any automation effort. For wishlists, which involve dynamic content and user interactions, building stable tests requires careful attention to detail.
Locator Strategy: Finding Wishlist Elements Reliably
The most common cause of test instability is brittle locators. When the UI changes, locators break.
- Prioritize Stable Attributes:
-
data-*attributes (e.g.,data-testid,data-cy,data-wishlist-item-id). These are designed for testing and are less likely to change. - Unique IDs: If available and stable, IDs are excellent. Avoid auto-generated IDs.
- CSS Selectors: Generally more robust than XPath, especially when using
data-*attributes or stable class names. - XPath: Powerful but can be brittle if not written carefully. Use it sparingly, preferably for complex relationships or when other options are unavailable. Avoid absolute XPath.
- Avoid Brittle Locators:
- Text content: Locators based on exact text can break easily with minor UI changes or internationalization.
- Index-based locators:
div:nth-child(3)is highly susceptible to changes in DOM structure. - Auto-generated class names: These often change with framework updates or styling modifications.
Example (Playwright - Web):
// Good: Using data-testid
await page.locator('[data-testid="add-to-wishlist-button"]').click();
await page.locator('[data-cy="wishlist-item-name"]').first().waitFor(); // Wait for at least one item
// Less Ideal: Using generic class names and index
// await page.locator('.product-card .btn-wishlist').first().click();
// Avoid: Using exact text (can break with localization or minor wording changes)
// await page.locator('text="Add to My Wishlist"').click();
Example (Appium - Mobile):
For mobile, you'll often use resource IDs, accessibility IDs, or XPath.
// Good: Using resource-id (Android)
MobileElement addToWishlistButton = driver.findElement(MobileBy.id("com.yourapp.package:id/add_to_wishlist_button"));
addToWishlistButton.click();
// Good: Using accessibility-id (iOS/Android)
MobileElement wishlistToggle = driver.findElement(MobileBy.AccessibilityId("Add to Wishlist"));
wishlistToggle.click();
// Less Ideal: Using XPath with text (can be brittle)
// MobileElement removeButton = driver.findElement(MobileBy.xpath("//android.widget.TextView[@text='Remove']"));
Handling Waits Effectively
Dynamic web and mobile applications load content asynchronously. Tests must wait for elements to be present, visible, or interactable before acting on them.
- Implicit Waits: Set a global timeout for the driver to wait for elements. Use with caution: Can slow down tests if elements consistently take longer than the timeout. Often leads to false negatives or masking of actual issues.
- Explicit Waits: The preferred method. Wait for a specific condition to be met.
- Visibility: Wait for an element to be visible on the screen.
- Clickability: Wait for an element to be visible and enabled, so it can be clicked.
- Presence: Wait for an element to be present in the DOM, even if not visible.
- Text Presence: Wait for an element to contain specific text.
Framework Support:
- Playwright & Cypress: Have built-in auto-waiting mechanisms. You generally don't need explicit waits for basic actions like
click()orfill(), as the framework automatically retries until the element is actionable or a default timeout is reached. This significantly reduces flakiness. - Selenium & Appium: Require explicit waits.
Example (Selenium - Web - Explicit Waits):
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
// ... inside your test method ...
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // 10-second timeout
// Wait for the 'Add to Wishlist' button to be clickable
WebElement addToWishlistButton = wait.until(
ExpectedConditions.elementToBeClickable(By.cssSelector("[data-testid='add-to-wishlist-button']"))
);
addToWishlistButton.click();
// Wait for at least one item to appear in the wishlist (e.g., by its name element)
wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-cy='wishlist-item-name']"))
);
Example (Playwright - Web - Auto-Waiting):
// Playwright automatically waits for elements to be actionable before performing actions
await page.locator('[data-testid="add-to-wishlist-button"]').click();
// You can still add explicit waits if needed for specific conditions
await expect(page.locator('[data-cy="wishlist-item-name"]')).toHaveCount(1); // Assert that exactly one item is visible
Handling Test Data: Setup and Teardown
Wishlist tests often require specific data conditions: a user account, products available, products not available, etc. Robust test data management is key.
- User Accounts:
- Pre-seeded Accounts: Have dedicated test user accounts ready in your test database.
- On-the-fly Creation: If your application has a robust signup flow, automate user creation before your wishlist tests run. Ensure you have a teardown process to delete these users afterward.
- Product Data:
- Stable Test Products: Use products in your test environment that are unlikely to be removed or changed frequently. Assign them stable identifiers.
- Dynamic Product Creation: If your tests need specific product configurations (e.g., out-of-stock, specific variations), consider creating these products programmatically before the test and cleaning them up afterward.
- Teardown Strategy:
- Crucial for Isolation: Each test should ideally start from a known, clean state.
- Cleanup: After each test or test suite, remove items from wishlists, delete created users, or revert any data changes made.
- Error Handling: Ensure cleanup happens even if a test fails. Use
try-finallyblocks or framework-specific teardown hooks.
Example (Conceptual - Python with Selenium):
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Fixture for setting up and tearing down the driver
@pytest.fixture(scope="function")
def driver():
# Setup: Initialize driver, login user
driver = webdriver.Chrome()
driver.implicitly_wait(5) # Example implicit wait
login_user(driver, "testuser_wishlist@example.com", "password123") # Assume this helper function exists
yield driver
# Teardown: Clear wishlist, logout
clear_wishlist(driver, "testuser_wishlist@example.com") # Assume this helper function exists
logout_user(driver)
driver.quit()
def test_add_item_to_wishlist(driver):
# Test logic: Navigate to product, add to wishlist, verify
driver.get("http://your-ecommerce.com/products/123")
add_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-testid='add-to-wishlist-button']"))
)
add_button.click()
driver.get("http://your-ecommerce.com/wishlist")
wishlist_item_name = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "[data-cy='wishlist-item-name']"))
)
assert "Product Name" in wishlist_item_name.text
def login_user(driver, email, password):
print(f"Logging in user: {email}")
driver.get("http://your-ecommerce.com/login")
driver.find_element(By.ID, "email").send_keys(email)
driver.find_element(By.ID, "password").send_keys(password)
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
WebDriverWait(driver, 10).until(EC.url_contains("/dashboard")) # Wait for login confirmation
def clear_wishlist(driver, user_email):
# Logic to programmatically clear the wishlist for the user via API or UI
# This is crucial for test isolation. If this fails, the next test might see old data.
print(f"Clearing wishlist for {user_email}...")
# Example: Navigate to wishlist, find remove buttons, click them, wait for confirmation.
# Or, ideally, call a backend API: requests.post(API_URL + "/clear_wishlist", json={"user": user_email})
def logout_user(driver):
print("Logging out user.")
# Logout logic...
Addressing Flakiness and Retries
Even with good practices, some tests might occasionally fail due to transient issues (network glitches, slow server responses).
- Retry Mechanisms: Most test runners and frameworks support retry configurations.
- Run-level Retries: Configure your test runner (e.g.,
pytest-rerunfailures, TestNGretryAnalyzer) to retry a failed test a few times. - Test-level Retries: Some frameworks allow specifying retries per test case.
- Analyze Failures: Don't blindly retry. Investigate *why* a test is failing. If it fails consistently after retries, it indicates a genuine bug or a deep-seated instability that needs fixing.
- Use Autonomous Tools for Bootstrapping: Tools like SUSATest can generate initial tests that are often more resilient because they incorporate best practices for waits and element interaction learned during exploration. This reduces the amount of manual debugging needed for flaky locators or timing issues in the early stages.
Automating Wishlist Flows: Step-by-Step Examples
Let's walk through a couple of common wishlist scenarios using Playwright for web and Appium for mobile.
Scenario 1: Add Item to Wishlist and Verify (Web - Playwright)
Goal: User logs in, navigates to a product, adds it to the wishlist, and verifies it appears on the wishlist page.
// test/wishlist.spec.js
import { test, expect } from '@playwright/test';
test.describe('Wishlist Functionality', () => {
let testProductId = 'PRODUCT_ID_123'; // Use a stable test product ID
let testProductName = 'Example Product Name'; // Use the expected name for verification
test('should allow adding an item to the wishlist', async ({ page }) => {
// --- Test Setup ---
// Login (replace with your actual login flow or use existing session)
await page.goto('/login');
await page.fill('[data-testid="email-input"]', 'testuser@example.com');
await page.fill('[data-testid="password-input"]', 'password123');
await page.click('[data-testid="login-button"]');
await expect(page).toHaveURL('/dashboard'); // Verify successful login
// --- Core Test Logic ---
// Navigate to the product page
await page.goto(`/products/${testProductId}`);
// Add the item to the wishlist
const addToWishlistButton = page.locator('[data-testid="add-to-wishlist-button"]');
await expect(addToWishlistButton).toBeVisible();
await addToWishlistButton.click();
// Optionally, wait for a success indicator (toast message, button state change)
await expect(page.locator('[data-testid="wishlist-success-message"]')).toBeVisible({ timeout: 10000 });
// Navigate to the wishlist page
await page.goto('/wishlist');
// Verify the item is present in the wishlist
const wishlistItem = page.locator(`[data-testid="wishlist-item"][data-product-id="${testProductId}"]`);
await expect(wishlistItem).toBeVisible();
await expect(wishlistItem.locator('[data-testid="wishlist-item-name"]')).toHaveText(testProductName);
await expect(wishlistItem.locator('[data-testid="wishlist-item-price"]')).toContainText('$'); // Check for price presence
// --- Test Teardown (Optional but recommended for isolation) ---
// Remove the item from the wishlist via UI or API
await wishlistItem.locator('[data-testid="remove-wishlist-item"]').click();
await expect(wishlistItem).not.toBeVisible({ timeout: 5000 }); // Verify removal
});
});
// Helper function (conceptual) for login if needed elsewhere
async function login(page, email, password) {
await page.goto('/login');
await page.fill('[data-testid="email-input"]', email);
await page.fill('[data-testid="password-input"]', password);
await page.click('[data-testid="login-button"]');
await expect(page).toHaveURL('/dashboard');
}
Scenario 2: Remove Item from Wishlist (Mobile - Appium with Java)
Goal: User logs in, adds an item to the wishlist, then removes it, verifying the wishlist is updated.
// src/test/java/com/yourapp/tests/WishlistTest.java
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
public class WishlistTest {
private AppiumDriver<MobileElement> driver;
private WebDriverWait wait;
// --- Test Setup ---
@BeforeClass
public void setUp() throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
// --- Configure capabilities for your device/emulator ---
caps.setCapability("platformName", "Android");
caps.setCapability("platformVersion", "11.0"); // Example version
caps.setCapability("deviceName", "Android Emulator"); // Example device name
caps.setCapability("appPackage", "com.yourapp.package"); // Your app's package name
caps.setCapability("appActivity", "com.yourapp.package.MainActivity"); // Your app's main activity
caps.setCapability("automationName", "UiAutomator2"); // For Android
// caps.setCapability("udid", "YOUR_DEVICE_UDID"); // If using a real device
// --- Initialize Driver ---
driver = new AppiumDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), caps); // Appium server URL
wait = new WebDriverWait(driver, 15); // 15-second wait timeout
// --- Login ---
login("testuser@example.com", "password123");
}
// --- Core Test Logic ---
@Test
public void testRemoveItemFromWishlist() {
String productId = "prod_456"; // Example product identifier
String expectedProductName = "Awesome Gadget";
// Navigate to product details page
navigateToProduct(productId);
// Add item to wishlist
MobileElement addToWishlistButton = wait.until(ExpectedConditions.elementToBeClickable(
MobileBy.AccessibilityId("Add to Wishlist") // Use Accessibility ID or Resource ID
));
addToWishlistButton.click();
// Wait for confirmation (e.g., button changes state, toast message)
wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AccessibilityId("Remove from Wishlist")));
// Navigate to Wishlist screen
navigateToWishlist();
// Verify item is present
MobileElement wishlistItem = wait.until(ExpectedConditions.visibilityOfElementLocated(
MobileBy.id("com.yourapp.package:id/wishlistItemName") // Example resource ID
));
// Assert item name is correct (adjust locator as needed)
// Assert.assertTrue(wishlistItem.getText().contains(expectedProductName), "Item not found in wishlist");
// Remove the item
MobileElement removeButton = wait.until(ExpectedConditions.elementToBeClickable(
MobileBy.id("com.yourapp.package:id/removeWishlistItemButton") // Example resource ID for remove button
));
removeButton.click();
// Verify item is removed (e.g., wishlist becomes empty or item disappears)
wait.until(ExpectedConditions.invisibilityOfElementLocated(
MobileBy.id("com.yourapp.package:id/wishlistItemName") // Locator for the item name
));
// Or assert that an "empty wishlist" message is visible
// MobileElement emptyMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(
// MobileBy.id("com.yourapp.package:id/emptyWishlistMessage")));
// Assert.assertEquals(emptyMessage.getText(), "Your wishlist is empty.");
}
// --- Helper Methods ---
private void login(String email, String password) {
System.out.println("Logging in...");
// Implement actual login steps using driver
// Example: fill username, fill password, click login button
// wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.id("some_dashboard_element")));
}
private void navigateToProduct(String productId) {
System.out.println("Navigating to product: " + productId);
// Implement navigation to product details page
driver.get("app://your-ecommerce.com/products/" + productId); // Example deep link or navigation
}
private void navigateToWishlist() {
System.out.println("Navigating to wishlist...");
// Implement navigation to the wishlist screen
driver.findElement(MobileBy.AccessibilityId("Main Menu")).click(); // Example: Open menu
wait.until(ExpectedConditions.
Test Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free