Bird
0
0

You want to write a Selenium Java test that clicks Cancel on a confirmation alert only if the alert text contains the word "Delete". Which code snippet correctly implements this?

hard📝 Application Q15 of 15
Selenium Java - Handling Windows, Frames, and Alerts
You want to write a Selenium Java test that clicks Cancel on a confirmation alert only if the alert text contains the word "Delete". Which code snippet correctly implements this?
AAlert alert = driver.switchTo().alert(); if (alert.getText() == "Delete") { alert.accept(); } else { alert.dismiss(); }
BAlert alert = driver.switchTo().alert(); alert.dismiss(); if (alert.getText().contains("Delete")) { alert.accept(); }
CAlert alert = driver.switchTo().alert(); if (alert.getText().contains("Delete")) { alert.dismiss(); } else { alert.accept(); }
DAlert alert = driver.switchTo().alert(); alert.accept(); alert.dismiss();
Step-by-Step Solution
Solution:
  1. Step 1: Check alert text for "Delete" substring

    Use alert.getText().contains("Delete") to detect if alert text includes "Delete".
  2. Step 2: Dismiss alert if condition true, else accept

    If text contains "Delete", call dismiss() to click Cancel; otherwise, call accept().
  3. Final Answer:

    Alert alert = driver.switchTo().alert(); if (alert.getText().contains("Delete")) { alert.dismiss(); } else { alert.accept(); } -> Option C
  4. Quick Check:

    Use contains() and dismiss() for conditional cancel [OK]
Quick Trick: Use getText().contains() before dismiss() or accept() [OK]
Common Mistakes:
  • Using == instead of contains() for string check
  • Calling dismiss() before checking alert text
  • Calling accept() and dismiss() both without condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes