Skip to content

added java example code for alert #1977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 27, 2024

Conversation

pallavigitwork
Copy link
Member

@pallavigitwork pallavigitwork commented Sep 27, 2024

User description

Thanks for contributing to the Selenium site and documentation!
A PR well described will help maintainers to review and merge it quickly

Before submitting your PR, please check our contributing guidelines.
Avoid large PRs, and help reviewers by making them as simple and short as possible.

Description

added java example code for alert

Motivation and Context

added java example code for alert

Types of changes

  • Change to the site (I have double-checked the Netlify deployment, and my changes look good)
  • Code example added (and I also added the example to all translated languages)
  • Improved translation
  • Added new translation (and I also added a notice to each document missing translation)

Checklist

  • I have read the contributing document.
  • I have used hugo to render the site/docs locally and I am sure it works.

PR Type

enhancement, documentation


Description

  • Added a new Java test class AlertsTest to demonstrate handling of alerts, confirms, and prompts using Selenium WebDriver.
  • Updated the documentation in multiple languages (English, Japanese, Portuguese, Chinese) to reference the new Java test examples.
  • Replaced inline Java code examples with references to the new test class in the documentation.

Changes walkthrough 📝

Relevant files
Enhancement
AlertsTest.java
Add Java test examples for handling alerts                             

examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java

  • Added a new Java test class AlertsTest.
  • Implemented methods to handle alerts, confirms, and prompts.
  • Used WebDriver, JavascriptExecutor, and WebDriverWait.
  • Included assertions to verify alert text.
  • +88/-4   
    Documentation
    alerts.en.md
    Update Java alert examples in English documentation           

    website_and_docs/content/documentation/webdriver/interactions/alerts.en.md

  • Updated Java code examples to use new test class.
  • Replaced inline code with references to the Java test file.
  • +9/-42   
    alerts.ja.md
    Update Java alert examples in Japanese documentation         

    website_and_docs/content/documentation/webdriver/interactions/alerts.ja.md

  • Updated Java code examples to use new test class.
  • Replaced inline code with references to the Java test file.
  • +9/-42   
    alerts.pt-br.md
    Update Java alert examples in Portuguese documentation     

    website_and_docs/content/documentation/webdriver/interactions/alerts.pt-br.md

  • Updated Java code examples to use new test class.
  • Replaced inline code with references to the Java test file.
  • +9/-43   
    alerts.zh-cn.md
    Update Java alert examples in Chinese documentation           

    website_and_docs/content/documentation/webdriver/interactions/alerts.zh-cn.md

  • Updated Java code examples to use new test class.
  • Replaced inline code with references to the Java test file.
  • +9/-42   

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    Copy link

    netlify bot commented Sep 27, 2024

    👷 Deploy request for selenium-dev pending review.

    Visit the deploys page to approve it

    Name Link
    🔨 Latest commit 3a7737e

    @qodo-merge-pro qodo-merge-pro bot added documentation Improvements or additions to documentation enhancement New feature or request Review effort [1-5]: 2 labels Sep 27, 2024
    Copy link
    Contributor

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Resource Management
    The WebDriver instance is not closed in a finally block, which may lead to resource leaks if an exception occurs.

    Test Structure
    The test method contains multiple assertions and scenarios, which violates the single responsibility principle for unit tests.

    Copy link
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Best practice
    Use a try-finally block to ensure proper resource cleanup

    Consider using a try-finally block to ensure that the WebDriver is always closed,
    even if an exception occurs during the test execution. This helps prevent resource
    leaks and improves the robustness of the test.

    examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java [30-89]

     @Test
     public void testForAlerts() throws Exception {
    -    ChromeOptions chromeOptions = new ChromeOptions();
    -    chromeOptions.addArguments("disable-search-engine-choice-screen");
    -    WebDriver driver = new ChromeDriver(chromeOptions);
    -    
    -    driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
    -    driver.manage().window().maximize();
    -    //Navigate to Url
    -    driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");
    -    
    -    // ... rest of the test code ...
    -    
    -    //quit the browser
    -    driver.quit();
    +    WebDriver driver = null;
    +    try {
    +        ChromeOptions chromeOptions = new ChromeOptions();
    +        chromeOptions.addArguments("disable-search-engine-choice-screen");
    +        driver = new ChromeDriver(chromeOptions);
    +        
    +        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
    +        driver.manage().window().maximize();
    +        //Navigate to Url
    +        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");
    +        
    +        // ... rest of the test code ...
    +        
    +    } finally {
    +        if (driver != null) {
    +            driver.quit();
    +        }
    +    }
     }
    Suggestion importance[1-10]: 9

    Why: This suggestion addresses a critical issue of resource management by ensuring that the WebDriver is always closed, even if an exception occurs. This prevents resource leaks and enhances the robustness of the test.

    9
    Use explicit waits consistently instead of implicit waits

    Instead of using Thread.sleep() or implicitlyWait(), consider using WebDriverWait
    consistently throughout the test for better reliability and performance. This
    approach helps avoid fixed delays and makes the test more robust against timing
    issues.

    examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java [37]

    -driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
    +WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Replacing implicit waits with explicit waits improves test reliability and performance by avoiding fixed delays and making the test more robust against timing issues.

    8
    Enhancement
    Extract alert handling logic into separate methods for improved readability and maintainability

    Consider extracting the alert handling logic into separate methods for each type of
    alert (simple alert, confirm, prompt). This will improve code readability and
    maintainability by reducing duplication and separating concerns.

    examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java [42-87]

    -//Simple Alert
    -//Click the link to activate the alert
    -JavascriptExecutor js = (JavascriptExecutor) driver;
    -//execute js for alert
    -js.executeScript("alert('Sample Alert');");
    -WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
    -//Wait for the alert to be displayed and store it in a variable
    -wait.until(ExpectedConditions.alertIsPresent());
    +private void handleSimpleAlert(WebDriver driver, JavascriptExecutor js) {
    +    js.executeScript("alert('Sample Alert');");
    +    Alert alert = waitForAlert(driver);
    +    assertEquals("Sample Alert", alert.getText());
    +    alert.accept();
    +}
     
    -Alert alert=driver.switchTo().alert();
    -//Store the alert text in a variable and verify it
    -String text = alert.getText();
    -assertEquals(text,"Sample Alert"); 
    -//Press the OK button
    -alert.accept();
    -        
    -//Confirm
    -//execute js for confirm
    -js.executeScript("confirm('Are you sure?');");
    -//Wait for the alert to be displayed
    -wait = new WebDriverWait(driver, Duration.ofSeconds(30));
    -wait.until(ExpectedConditions.alertIsPresent());
    +private void handleConfirm(WebDriver driver, JavascriptExecutor js) {
    +    js.executeScript("confirm('Are you sure?');");
    +    Alert alert = waitForAlert(driver);
    +    assertEquals("Are you sure?", alert.getText());
    +    alert.dismiss();
    +}
     
    +private void handlePrompt(WebDriver driver, JavascriptExecutor js) {
    +    js.executeScript("prompt('What is your name?');");
    +    Alert alert = waitForAlert(driver);
    +    assertEquals("What is your name?", alert.getText());
    +    alert.sendKeys("Selenium");
    +    alert.accept();
    +}
     
    -alert = driver.switchTo().alert();
    -//Store the alert text in a variable and verify it
    -text = alert.getText();
    -assertEquals(text,"Are you sure?"); 
    -//Press the Cancel button
    -alert.dismiss();
    +private Alert waitForAlert(WebDriver driver) {
    +    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
    +    return wait.until(ExpectedConditions.alertIsPresent());
    +}
     
    -//Prompt
    -//execute js for prompt
    -js.executeScript("prompt('What is your name?');");
    -//Wait for the alert to be displayed and store it in a variable
    -wait = new WebDriverWait(driver, Duration.ofSeconds(30));
    -wait.until(ExpectedConditions.alertIsPresent());
    +@Test
    +public void testForAlerts() throws Exception {
    +    // ... existing setup code ...
     
    -alert = driver.switchTo().alert();
    -//Store the alert text in a variable and verify it
    -text = alert.getText();
    -assertEquals(text,"What is your name?"); 
    -//Type your message
    -alert.sendKeys("Selenium");
    -//Press the OK button
    -alert.accept();
    +    JavascriptExecutor js = (JavascriptExecutor) driver;
    +    handleSimpleAlert(driver, js);
    +    handleConfirm(driver, js);
    +    handlePrompt(driver, js);
     
    +    // ... existing teardown code ...
    +}
    +
    Suggestion importance[1-10]: 7

    Why: This suggestion enhances code readability and maintainability by reducing duplication and separating concerns, making it easier to manage and update the alert handling logic.

    7
    Maintainability
    Use a constant for WebDriverWait timeout duration

    Consider using a constant for the timeout duration in WebDriverWait to improve
    maintainability and consistency. This makes it easier to adjust the timeout value
    across the entire test if needed.

    examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java [47]

    -WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
    +private static final Duration TIMEOUT = Duration.ofSeconds(30);
    +// ...
    +WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
    Suggestion importance[1-10]: 6

    Why: Using a constant for the timeout duration improves maintainability and consistency, making it easier to adjust the timeout value across the entire test if needed.

    6

    💡 Need additional feedback ? start a PR chat

    @pallavigitwork pallavigitwork requested review from titusfortner and harsha509 and removed request for titusfortner September 27, 2024 13:55
    Copy link
    Member

    @harsha509 harsha509 left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Thank you @pallavigitwork !

    @harsha509 harsha509 merged commit 8389e17 into SeleniumHQ:trunk Sep 27, 2024
    9 checks passed
    @pallavigitwork
    Copy link
    Member Author

    Thanks @harsha509 :)

    @harsha509 harsha509 mentioned this pull request Feb 8, 2025
    6 tasks
    @pallavigitwork pallavigitwork deleted the pallavi-alert-java branch March 25, 2025 21:57
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    documentation Improvements or additions to documentation enhancement New feature or request Review effort [1-5]: 2
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants