Bird
0
0

Find the bug in this Selenium Java code snippet for form testing: driver.findElement(By.id("username")).sendKeys("user1"); driver.findElement(By.id("password")).sendKeys("pass1"); driver.findElement(By.id("loginBtn")).click(); String alertText = driver.switchTo().alert().getText(); System.out.println(alertText);

medium📝 Debug Q7 of 15
Selenium Java - Handling Form Elements
Find the bug in this Selenium Java code snippet for form testing: driver.findElement(By.id("username")).sendKeys("user1"); driver.findElement(By.id("password")).sendKeys("pass1"); driver.findElement(By.id("loginBtn")).click(); String alertText = driver.switchTo().alert().getText(); System.out.println(alertText);
ANo wait for alert to appear before switching
BIncorrect locator for login button
CsendKeys called on wrong elements
DMissing driver.quit() call
Step-by-Step Solution
Solution:
  1. Step 1: Understand alert handling

    Switching to alert immediately may fail if alert is not yet present.
  2. Step 2: Identify missing wait

    Code lacks explicit wait to pause until alert appears, causing errors.
  3. Final Answer:

    No wait for alert to appear before switching -> Option A
  4. Quick Check:

    Always wait for alert before switchTo() [OK]
Quick Trick: Use waits before switching to alerts to avoid exceptions [OK]
Common Mistakes:
MISTAKES
  • Switching to alert too early
  • Assuming alert appears instantly
  • Ignoring need for waits in dynamic pages

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes