Level 3 · Core automation

Selenium Masterclass

Concept, why it matters, code, expected result, common mistakes and the interview question — for every Selenium area that shows up in real interviews.

Locator strategy

Pick the most stable locator available: id/data-test → CSS → relative XPath. XPath is only a last resort, never a first instinct.

Why it is required: Locator quality is the single biggest driver of maintenance cost in a UI suite.

javaLocator strategy · example
1// Best → worst
2By.id("checkout"); // stable, fastest
3By.cssSelector("[data-test='checkout']"); // preferred contract
4By.cssSelector("form.cart button.primary"); // structural, ok
5By.xpath("//label[text()='Card']/following::input[1]"); // last resort
6By.xpath("/html/body/div[3]/div[2]/form/button"); // never

Expected result

Locators that survive UI refactors and read clearly in page objects.

Common mistakes

  • Absolute XPath copied from browser devtools
  • Locators built on auto-generated class names (css-1x9f7t)
  • Text-based locators on a localised application

Interview question

CSS selector vs XPath — which do you prefer and why?

Debug this Selenium code

Read the snippet, spot the problems, then reveal the answer. These are the exact code reviews you get asked to do in a technical round.

Why is this login test flaky?

java
1driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
2driver.get("https://app.example.com/login");
3Thread.sleep(3000);
4driver.findElement(By.id("user")).sendKeys("admin");
5driver.findElement(By.id("pass")).sendKeys("secret");
6driver.findElement(By.id("submit")).click();
7Assert.assertTrue(driver.findElement(By.id("dashboard")).isDisplayed());

Why does this fail in parallel execution?

java
1public class BaseTest {
2 public static WebDriver driver;
3
4 @BeforeMethod
5 public void setUp() {
6 driver = new ChromeDriver();
7 }
8
9 @AfterMethod
10 public void tearDown() {
11 driver.quit();
12 }
13}