Repaso
Español
TestingIntermediateTST-34

Why is Thread.sleep(5000) a bad way to wait in UI tests, and what is better?

Options

  1. It always waits fully; use explicit waits instead (Correct option)
  2. It crashes the browser when the time is long
  3. Selenium forbids it in all of its drivers
  4. It is the best approach for slow web pages

Answer

It always waits the full time (slow) and can still be too short (flaky); use explicit waits (WebDriverWait with expected conditions) that continue as soon as the condition is true

Why

Pages load asynchronously, so tests must wait for elements. A fixed sleep is either too long (slows the suite) or too short (random failures).

Explicit wait: new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(...)) polls until the condition is true or times out.

Implicit waits apply globally to element lookups; do not mix implicit and explicit waits, since the total time becomes unpredictable.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement banner = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("success")));

Remember

Wait for a condition, not for a fixed time.

Key terms

Practice this question in Repaso