Skip to main content
SeleniumDecoded
Back to Challenges

Replace Brittle Locators

beginner Java 10 min

A checkout test uses absolute XPath and styling classes copied from DevTools. Rewrite the locators so a redesign will not break them.

The Scenario

The front-end team is moving from Tailwind utility classes to a component library next sprint. Every class name in the markup will change, and the wrapper <div> structure will too. The checkout test uses locators copied from DevTools’ “Copy XPath” and “Copy selector”.

Your Task

Replace each locator with one that depends only on attributes that will not change: form names, test ids, element types, and product-critical text. Keep the assertions.

What Good Looks Like

  • No absolute XPath, no styling classes, no positional nth-child.
  • Locators declared once as By constants, not inline.
  • A wait on the total, since applying a coupon is asynchronous.

Your task

A checkout test uses absolute XPath and styling classes copied from DevTools. Rewrite the locators so a redesign will not break them.

Problem Code
// HTML under test (abridged):
// <form id="checkout-form">
//   <input name="promoCode" class="mt-4 w-full rounded border px-3" placeholder="Promo code">
//   <button class="flex items-center btn btn-secondary">Apply</button>
//   <div class="flex justify-between text-lg font-semibold">
//     <span>Total</span><span data-testid="order-total">$99.00</span>
//   </div>
//   <button type="submit" class="btn btn-primary w-full">Place order</button>
// </form>

driver.findElement(By.xpath("/html/body/div[2]/main/form/input")).sendKeys("SAVE10");
driver.findElement(By.cssSelector(".flex.items-center.btn.btn-secondary")).click();
String total = driver.findElement(By.xpath("/html/body/div[2]/main/form/div[3]/span[2]")).getText();
assertEquals("$89.00", total);
driver.findElement(By.cssSelector("form > button:nth-child(4)")).click();

Need Help?

Solution

Try to solve the challenge yourself before revealing the solution.

Lessons that cover this