Selenium · Browser automation foundations
What does a first reliable Selenium test look like?
Short answer
Create a driver, navigate, locate elements by stable attributes, act, wait for the expected state, assert, and always quit the driver in cleanup so sessions do not leak.
A first test should prove the full loop without hiding failures. Use a real page, one clear action and one observable outcome. Avoid sleeps and avoid assertions on transient loading text.
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void userCanSignIn() {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com/login");
driver.findElement(By.id("email")).sendKeys("asha@example.com");
driver.findElement(By.id("password")).sendKeys("correct-horse");
driver.findElement(By.cssSelector("[data-testid='sign-in']")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.urlContains("/dashboard"));
Assert.assertTrue(driver.getTitle().contains("Dashboard"));
} finally {
driver.quit();
}
}
}- Use a stable locator such as id or data-testid rather than visible text where possible
- Wait for the outcome you assert on, not for an arbitrary delay
- Call quit in a finally block or in framework cleanup so the browser process exits
- Keep the first test independent of other tests and of execution order
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is quit preferred over close?
- 2Why is asserting on the final URL better than sleeping?
- 3What makes a locator stable?
- 4How would you move driver setup out of the test?
Say it in the interview
My first test follows the real user loop: create a driver, navigate, fill the form, click, wait for the resulting URL, then assert the dashboard title. The wait targets the outcome, not a fixed delay. Cleanup is in a finally block with quit so a failure cannot leak a browser session. Once that works, I move driver creation into a base class or factory.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.