Selenium · Browser automation foundations
How should you assert in a Selenium test?
Short answer
Assert on user-observable outcomes after synchronising on them. Use hard assertions for flow-critical checks and soft assertions only when you need to collect several independent failures in one test.
A Selenium assertion is only as good as its timing. Asserting immediately after a click often checks the old page. Wait for the condition first, then assert. The assertion should describe a behaviour, not an implementation detail such as a CSS class.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement status = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[role='status']")));
Assert.assertEquals(status.getText(), "Order placed");
SoftAssert soft = new SoftAssert();
soft.assertTrue(driver.getCurrentUrl().contains("/orders"));
soft.assertTrue(driver.getTitle().contains("Orders"));
soft.assertAll();- Hard assertions stop the test on failure, which is correct when later steps depend on the result
- Soft assertions collect multiple failures but can hide a broken flow if overused
- AssertJ and Hamcrest give clearer failure messages than raw boolean checks
- Include the actual value and context in the failure message
- Never assert on a value that can legitimately change between environments without normalising it
Text assertions are useful for user-visible contracts but brittle for localisation and copy changes. For status codes and state, assert on URL, API responses or accessible roles where possible. Use the page object to expose state, then assert in the test.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1When would you use a soft assertion?
- 2Why is asserting immediately after a click unreliable?
- 3How do you make failure messages useful?
- 4What is wrong with asserting on a CSS class?
Say it in the interview
I wait for the observable state and then assert on it, so a pass cannot come from checking the previous page. Hard assertions are the default because later steps usually depend on earlier ones. I use soft assertions only for independent checks that should all be reported together. I prefer assertions on URL, accessible text or API state over CSS classes, and I make the failure message include the actual value.
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.