Certainly! Let’s dive into Assignment 1 and Assignment 2 based on today’s session on handling mouse actions using Selenium WebDriver in Java. We’ll provide detailed explanations and sample code to help you successfully complete these assignments.
Table of Contents
1. Assignment 1: Double Click Action and Drag and Drop
• Objective
Automate the following actions using Selenium WebDriver:
- Double Click Action:
- Clear the text from the first input box.
- Enter new text into the first input box.
- Perform a double-click action on the “Copy Text” button.
- Verify that the text has been copied to the second input box.
- Drag and Drop Action:
- Drag an item (e.g., “Rome”) from one list and drop it into another list (e.g., “Italy”).
- Verify that the item has been successfully moved.
• Prerequisites
- Selenium WebDriver: Ensure you have Selenium WebDriver set up in your Java project.
- ChromeDriver: Make sure you have the correct version of ChromeDriver installed and its path is set correctly.
- Java Development Kit (JDK): Ensure JDK is installed on your machine.
- IDE: Use an IDE like IntelliJ IDEA, Eclipse, or any other of your choice.
• Implementation Steps
- Handling Double Click Action
- Setup and Configuration:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import java.util.concurrent.TimeUnit; public class DoubleClickAction { public static void main(String[] args) { // 1. Setup WebDriver System.setProperty("webdriver.chrome.driver", "path_to_chromedriver"); // Replace with your ChromeDriver path WebDriver driver = new ChromeDriver(); // 2. Configure WebDriver driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Implicit Wait try { // 3. Navigate to the Target Page driver.get("https://example.com/double-click-page"); // Replace with actual URL // 4. Switch to the iframe if the elements are inside a frame driver.switchTo().frame("iframeID_or_Name"); // Replace with actual frame ID or name // 5. Locate Elements WebElement boxOne = driver.findElement(By.xpath("//input[@id='field1']")); // Replace with actual XPath WebElement boxTwo = driver.findElement(By.xpath("//input[@id='field2']")); // Replace with actual XPath WebElement copyButton = driver.findElement(By.xpath("//button[@id='copy-button']")); // Replace with actual XPath // 6. Clear the first input box and enter new text boxOne.clear(); boxOne.sendKeys("Welcome"); // 7. Perform Double Click on the Copy Button Actions actions = new Actions(driver); actions.doubleClick(copyButton).perform(); // Alternatively, actions.doubleClick(copyButton).build().perform(); // 8. Verification: Check if the text has been copied to the second input box String copiedText = boxTwo.getAttribute("value"); // Using getAttribute since getText() won't work for input fields if ("Welcome".equals(copiedText)) { System.out.println("Double Click Action: Text copied successfully!"); } else { System.out.println("Double Click Action: Text copy failed."); } } catch (Exception e) { e.printStackTrace(); } finally { // 9. Close the Browser driver.quit(); } } }
- Explanation:
- WebDriver Setup:
- Initialize the ChromeDriver and configure it with implicit waits.
- Maximize the browser window for better visibility.
- Navigating to the Target Page:
- Replace “https://example.com/double-click-page” with the actual URL where your double-click functionality exists.
- Handling Frames:
- If your elements are inside an
<iframe>
, switch to it usingdriver.switchTo().frame("iframeID_or_Name");
. Replace “iframeID_or_Name” with the actual identifier. - If elements are not inside a frame, you can skip this step.
- If your elements are inside an
- Locating Elements:
- Use accurate XPath expressions to locate the first input box (
field1
), the second input box (field2
), and the “Copy Text” button (copy-button
). - Replace the XPath strings with the actual paths based on your application’s HTML structure.
- Use accurate XPath expressions to locate the first input box (
- Performing Actions:
- Clear and Enter Text: Clear any existing text in the first input box and enter “Welcome”.
- Double Click: Use the
Actions
class to perform a double-click on the “Copy Text” button. This action should trigger the JavaScript that copies the text from the first input box to the second.
- Verification:
- Retrieve the value from the second input box using
getAttribute("value")
sincegetText()
doesn’t work for input fields. - Compare the retrieved text with the expected value “Welcome” to verify the success of the double-click action.
- Retrieve the value from the second input box using
- WebDriver Setup:
- Setup and Configuration:
- Handling Drag and Drop Action
- Setup and Configuration:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import java.util.concurrent.TimeUnit; public class DragAndDropAction { public static void main(String[] args) { // 1. Setup WebDriver System.setProperty("webdriver.chrome.driver", "path_to_chromedriver"); // Replace with your ChromeDriver path WebDriver driver = new ChromeDriver(); // 2. Configure WebDriver driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Implicit Wait try { // 3. Navigate to the Drag and Drop Demo Page driver.get("https://example.com/drag-drop-demo"); // Replace with actual URL // 4. Switch to the iframe if the elements are inside a frame driver.switchTo().frame("iframeID_or_Name"); // Replace with actual frame ID or name // 5. Locate Source and Target Elements WebElement sourceRome = driver.findElement(By.xpath("//div[@id='rome']")); // Replace with actual XPath WebElement targetItaly = driver.findElement(By.xpath("//div[@id='italy']")); // Replace with actual XPath // 6. Perform Drag and Drop Actions actions = new Actions(driver); actions.dragAndDrop(sourceRome, targetItaly).perform(); // Alternatively, actions.dragAndDrop(sourceRome, targetItaly).build().perform(); // 7. Verification: Check if the element has been moved // This can vary based on the application's implementation. One way is to check if the source element is no longer present in its original location. boolean isMoved = false; try { driver.findElement(By.xpath("//div[@id='rome']")); // Try locating in original place } catch (Exception e) { isMoved = true; // If not found, it has been moved } if (isMoved) { System.out.println("Drag and Drop Action: Element moved successfully!"); } else { System.out.println("Drag and Drop Action: Element move failed."); } } catch (Exception e) { e.printStackTrace(); } finally { // 8. Close the Browser driver.quit(); } } }
- Explanation:
- WebDriver Setup:
- Initialize the ChromeDriver and configure it with implicit waits.
- Maximize the browser window for better visibility.
- Navigating to the Drag and Drop Demo Page:
- Replace “https://example.com/drag-drop-demo” with the actual URL where your drag and drop functionality exists.
- Handling Frames:
- If your elements are inside an
<iframe>
, switch to it usingdriver.switchTo().frame("iframeID_or_Name");
. Replace “iframeID_or_Name” with the actual id or name of the iframe. - If elements are not inside a frame, you can skip this step.
- If your elements are inside an
- Locating Elements:
- Use accurate XPath expressions to locate the source element (e.g., “Rome”) and the target element (e.g., “Italy”).
- Replace the XPath strings with the actual paths based on your application’s HTML structure.
- Performing Actions:
- Drag and Drop: Use the
Actions
class to perform a drag-and-drop action from the source element to the target element.
- Drag and Drop: Use the
- Verification:
- Simple Verification: Check if the source element is no longer present in its original location. This indicates a successful move.
- Advanced Verification: Depending on your application’s implementation, you might verify the presence of the element in the target container or check for specific success messages.
- WebDriver Setup:
- Setup and Configuration:
• Handling Frames
If your elements are within different frames (e.g., one element in Frame A and the target in Frame B), you’ll need to switch between frames accordingly. Here’s how you can handle drag and drop across frames:
// Switch to Frame A to locate the source element
driver.switchTo().frame("frameA");
// Locate the source element
WebElement sourceElement = driver.findElement(By.xpath("//div[@id='source']"));
// Switch back to the default content before switching to Frame B
driver.switchTo().defaultContent();
// Switch to Frame B to locate the target element
driver.switchTo().frame("frameB");
// Locate the target element
WebElement targetElement = driver.findElement(By.xpath("//div[@id='target']"));
// Perform Drag and Drop
Actions actions = new Actions(driver);
actions.dragAndDrop(sourceElement, targetElement).perform();
Note: Drag and drop across different frames can be more complex and might require additional handling based on the application’s structure.
2. Assignment 2: Handling an End-to-End Booking Application
• Objective
Automate the entire process of filling out a booking form that includes various elements such as radio buttons, checkboxes, input fields, dropdowns, auto-suggestions, and multiple date pickers. The goal is to:
- Interact with Various Web Elements:
- Select radio buttons (e.g., gender).
- Check checkboxes.
- Input text into fields (e.g., first name, last name).
- Handle dropdowns and auto-suggestions (e.g., selecting cities).
- Handle multiple date pickers for departure and return dates.
- Submit the Form:
- Click the “Place Order” or equivalent button to submit the form.
- Verification (Optional):
- Verify that the form submission was successful by checking for confirmation messages or redirects.
• Implementation Steps
- Setup and Configuration:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import java.time.Month; import java.util.List; import java.util.concurrent.TimeUnit; public class BookingFormAutomation { public static void main(String[] args) { // 1. Setup WebDriver System.setProperty("webdriver.chrome.driver", "path_to_chromedriver"); // Replace with your ChromeDriver path WebDriver driver = new ChromeDriver(); // 2. Configure WebDriver driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Implicit Wait try { // 3. Navigate to the Booking Form Page driver.get("https://example.com/booking-form"); // Replace with actual URL // 4. Interact with Web Elements // a. Select Radio Button (e.g., Gender) WebElement maleRadio = driver.findElement(By.xpath("//input[@name='gender'][@value='Male']")); maleRadio.click(); // b. Check Checkbox (e.g., Agree to Terms) WebElement termsCheckbox = driver.findElement(By.xpath("//input[@type='checkbox'][@id='agree']")); if (!termsCheckbox.isSelected()) { termsCheckbox.click(); } // c. Input Text into Fields WebElement firstName = driver.findElement(By.xpath("//input[@id='first-name']")); firstName.sendKeys("John"); WebElement lastName = driver.findElement(By.xpath("//input[@id='last-name']")); lastName.sendKeys("Doe"); WebElement email = driver.findElement(By.xpath("//input[@id='email']")); email.sendKeys("john.doe@example.com"); // d. Handle Dropdown (e.g., Country Selection) Select countryDropdown = new Select(driver.findElement(By.xpath("//select[@id='country']"))); countryDropdown.selectByVisibleText("United States"); // e. Handle Auto-Suggestions (e.g., From City) WebElement fromCityInput = driver.findElement(By.xpath("//input[@id='from-city']")); fromCityInput.sendKeys("Del"); // Wait for auto-suggestions to load (consider using explicit waits) Thread.sleep(2000); // Replace with explicit wait for better practice List fromSuggestions = driver.findElements(By.xpath("//ul[@id='from-city-suggestions']/li")); for (WebElement suggestion : fromSuggestions) { if (suggestion.getText().equals("Delhi")) { suggestion.click(); break; } } // f. Handle Auto-Suggestions (e.g., To City) WebElement toCityInput = driver.findElement(By.xpath("//input[@id='to-city']")); toCityInput.sendKeys("New"); Thread.sleep(2000); // Replace with explicit wait List toSuggestions = driver.findElements(By.xpath("//ul[@id='to-city-suggestions']/li")); for (WebElement suggestion : toSuggestions) { if (suggestion.getText().equals("New York")) { suggestion.click(); break; } } // g. Handle Date Pickers // Departure Date Picker selectDate(driver, "May", "2025", "20", "//input[@id='departure-date']"); // Return Date Picker selectDate(driver, "June", "2025", "15", "//input[@id='return-date']"); // h. Submit the Form WebElement submitButton = driver.findElement(By.xpath("//button[@id='place-order']")); submitButton.click(); // i. Verification (Optional) // Example: Check for confirmation message WebElement confirmationMessage = driver.findElement(By.xpath("//div[@class='confirmation']")); if (confirmationMessage.isDisplayed()) { System.out.println("Booking successfully submitted!"); } else { System.out.println("Booking submission failed."); } } catch (Exception e) { e.printStackTrace(); } finally { // 5. Close the Browser driver.quit(); } } /** * Method to select a specific date using the date picker UI. * * @param driver WebDriver instance * @param month Desired month (e.g., "May") * @param year Desired year (e.g., "2025") * @param day Desired day (e.g., "20") * @param dateInputXPath XPath of the date input field */ public static void selectDate(WebDriver driver, String month, String year, String day, String dateInputXPath) throws InterruptedException { // Click on the date picker input to open the calendar WebElement dateInput = driver.findElement(By.xpath(dateInputXPath)); dateInput.click(); // Initialize Actions class Actions actions = new Actions(driver); // Loop until the desired month and year are found while (true) { // Capture the currently displayed month and year String currentMonth = driver.findElement(By.xpath("//span[@class='ui-datepicker-month']")).getText(); String currentYear = driver.findElement(By.xpath("//span[@class='ui-datepicker-year']")).getText(); // Compare with the desired month and year int monthComparison = convertMonthToObject(month).compareTo(convertMonthToObject(currentMonth)); int yearComparison = Integer.parseInt(year) - Integer.parseInt(currentYear); if (yearComparison == 0) { if (monthComparison == 0) { break; // Desired month and year are displayed } else if (monthComparison > 0) { // Desired month is in the future; click next driver.findElement(By.xpath("//a[@title='Next']")).click(); } else { // Desired month is in the past; click previous driver.findElement(By.xpath("//a[@title='Prev']")).click(); } } else if (yearComparison > 0) { // Desired year is in the future; click next driver.findElement(By.xpath("//a[@title='Next']")).click(); } else { // Desired year is in the past; click previous driver.findElement(By.xpath("//a[@title='Prev']")).click(); } // Optional: Wait for the calendar to update Thread.sleep(1000); // Replace with explicit wait for better practice } // Select the desired day List allDates = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//a")); for (WebElement date : allDates) { if (date.getText().equals(day)) { date.click(); break; } } } /** * Converts a month name string to a Month enum object. * * @param monthStr Month name (e.g., "January") * @return Month enum object */ public static Month convertMonthToObject(String monthStr) { return Month.valueOf(monthStr.toUpperCase()); } }
- Explanation:
- WebDriver Setup:
- Initialize the ChromeDriver and configure it with implicit waits.
- Maximize the browser window for better visibility.
- Navigating to the Booking Form Page:
- Replace “https://example.com/booking-form” with the actual URL of your booking form.
- Interacting with Web Elements:
- Radio Buttons:
- Locate the radio button for gender (e.g., Male) and select it.
- Checkboxes:
- Locate and select the “Agree to Terms” checkbox if it’s not already selected.
- Input Fields:
- Enter text into the first name, last name, and email fields.
- Dropdowns:
- Use the Select class to handle standard dropdowns like country selection.
- Auto-Suggestions:
- For fields with auto-suggestions (e.g., From City and To City), enter partial text and select the desired option from the suggestions.
- Note: Replace the XPath expressions with those specific to your application.
- Radio Buttons:
- Handling Date Pickers:
- Utilize the
selectDate
method (defined within the class) to handle multiple date pickers for departure and return dates. - This method navigates through the calendar UI to select the desired date based on the provided month, year, and day.
- Utilize the
- Submitting the Form:
- Locate and click the “Place Order” button to submit the form.
- Verification:
- Optionally, verify that the booking was successful by checking for a confirmation message or any other success indicators.
- Handling Exceptions:
- The try-catch block ensures that any exceptions are caught and printed, preventing abrupt termination of the script.
- Closing the Browser:
- The finally block ensures that the browser is closed regardless of the test outcome.
- WebDriver Setup:
• Best Practices and Tips
- Use Explicit Waits Instead of
Thread.sleep()
:- Replace
Thread.sleep()
with explicit waits for better synchronization. - Example:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//your_xpath")));
- Replace
- Utilize Page Object Model (POM):
- For larger projects, consider implementing POM to enhance code maintainability and reusability.
- Create separate classes for different pages, encapsulating element locators and interaction methods.
- Handle Dynamic Elements:
- Ensure that your locators are robust and can handle dynamic changes in the DOM.
- Use relative XPath expressions or CSS selectors that are less likely to break with UI changes.
- Avoid Hardcoding Values:
- Instead of hardcoding input values, consider reading them from external sources like Excel files, JSON, or property files for better flexibility.
- Error Handling:
- Implement comprehensive error handling to manage unexpected scenarios gracefully.
- Use try-catch blocks around critical sections of your code.
- Logging:
- Incorporate logging mechanisms to track the flow of your tests and make debugging easier.
3. Best Practices Recap
- Use Explicit Waits Over
Thread.sleep()
:- Enhances synchronization and reduces test execution time.
- Example:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementID")));
- Prefer Reliable Locators:
- Use
By.id
orBy.name
when available. - Use descriptive XPath or CSS selectors.
- Avoid brittle locators that depend on dynamic attributes.
- Use
- Handle Exceptions Gracefully:
- Prevents abrupt test failures and allows for better debugging.
- Example:
try { // Interaction code } catch (NoSuchElementException e) { System.out.println("Element not found: " + e.getMessage()); }
- Avoid Hardcoding Values:
- Use variables or external data sources for input values.
- Parameterize test scripts.
- Maintain Clean and Readable Code:
- Use descriptive variable and method names.
- Comment complex logic or XPath expressions.
- Organize code into reusable methods or Page Object Model (POM) structures.
- Use Page Object Model (POM):
- Promotes reusability and separation of concerns.
- Create separate classes for each page.
- Encapsulate element locators and interaction methods within page classes.
- Regularly Update WebDriver and Browsers:
- Ensures compatibility and leverages the latest features and fixes.
- Securely Handle Credentials:
- Prevents exposure of sensitive information.
- Use environment variables or encrypted storage solutions.
- Validate Actions:
- Ensures that the intended actions (like selecting a checkbox) have been performed successfully.
- Example:
assert checkbox.isSelected() : "Checkbox was not selected.";
- Avoid Overcomplicating Locators:
- Use the simplest locator that uniquely identifies an element.
4. Additional Insights: Understanding build() vs. perform()
During the session, you discussed the difference between build()
and perform()
methods in the Actions class. Here’s a concise explanation to solidify your understanding:
build()
Method:- Purpose: Compiles all the actions into a single executable action.
- Usage: Useful when you want to define a sequence of actions first and execute them later.
- Example:
Action action = actions.doubleClick(element).build(); // Perform the action later action.perform();
perform()
Method:- Purpose: Executes the actions that have been defined.
- Usage: Can be used directly after defining the actions without explicitly calling
build()
. - Example:
actions.doubleClick(element).perform();
- Key Difference:
- While
build().perform()
explicitly compiles and then executes the actions,perform()
alone implicitly builds and executes the actions. In most cases, usingperform()
alone is sufficient and more concise.
- While
5. Conclusion
By completing these assignments, you’ve reinforced your understanding of handling various mouse actions using Selenium WebDriver’s Actions class in Java. Remember to:
- Practice Regularly: Implement these actions on different web applications to gain proficiency.
- Understand the HTML Structure: Knowing the DOM structure of the target application is crucial for accurate element identification.
- Adhere to Best Practices: Utilize explicit waits, maintain clean code, and implement error handling to create robust automation scripts.
Next Steps:
- Complete the Assignments:
- Implement the provided code samples.
- Customize the XPath expressions based on your application’s HTML structure.
- Run the scripts to ensure they perform as expected.
- Explore Advanced Mouse Actions:
- Handle scenarios involving multiple frames.
- Implement complex drag-and-drop actions.
- Work with sliders and other interactive elements.
- Integrate with Testing Frameworks:
- Incorporate TestNG or JUnit to structure your tests.
- Implement assertions for automated verifications.
- Learn Keyboard Actions:
- In the next session, delve into handling keyboard actions using the Actions class.
Happy Automating! 🚀