명시적 대기(Explicit Wait)는 웹 페이지 내 특정 요소에 적용되는 대기 방식으로, 설정된 조건이 충족될 때까지 코드 실행을 일시적으로 멈춥니다.
명시적 대기는 동적(dynamic)으로 작동합니다. 예를 들어 대기 시간을 15초로 설정했더라도, 그 시간이 지나기 전에 조건(요소가 클릭 가능해지거나, 화면에 보이거나, 선택 가능해지는 등)이 먼저 충족되면 즉시 다음 단계로 넘어갑니다. 이 덕분에 불필요한 대기 시간 없이 효율적인 테스트가 가능합니다.
명시적 대기가 더 유연한 이유
명시적 대기는 조건(condition)을 직접 지정할 수 있어 암묵적 대기(Implicit Wait)보다 훨씬 유연하고 커스터마이징하기 쉽습니다. 자주 사용되는 주요 예상 조건(Expected Conditions)은 다음과 같습니다.
1. textToBePresentInElement() — 특정 요소에 원하는 텍스트가 포함될 때까지 대기
w.until(ExpectedConditions.textToBePresentInElement(By.id("<<id expression>>"), "Tutorialspoint"));2. elementToBeClickable() — 특정 요소가 클릭 가능한 상태가 될 때까지 대기
w.until(ExpectedConditions.elementToBeClickable(By.id("<<id expression>>")));3. alertIsPresent() — 알림 팝업(alert)이 나타날 때까지 대기
w.until(ExpectedConditions.alertIsPresent()) != null);
4. frameToBeAvailableAndSwitchToIt() — 프레임이 사용 가능해지면 해당 프레임으로 전환
w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("<<frame id>>")));명시적 대기의 장단점
명시적 대기는 구현이 다소 복잡하다는 단점이 있지만, 실행 속도에는 영향을 주지 않으며 페이지 내 특정 요소에만 선택적으로 적용할 수 있다는 큰 장점이 있습니다.
또한, 설정된 최대 대기 시간이 초과되면 ElementNotVisibleException 예외가 발생합니다. 따라서 대기 시간을 현실적으로 설정하는 것이 중요합니다.
명시적 대기 실전 예제
아래는 자바(Java) 환경에서 명시적 대기를 선언하고, textToBePresentInElement 메서드를 활용해 특정 요소에 'Whiteboard'라는 텍스트가 나타날 때까지 기다리는 전체 코드입니다.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Wait;
public class Explictwt {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
// 모든 요소에 적용되는 암묵적 대기 (단위: 초)
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// 'Coding Ground' 링크 클릭
driver.findElement(By.xpath("//span[text()='Coding Ground']")).click();
// 명시적 대기 선언 (최대 10초)
WebDriverWait w = new WebDriverWait(driver,10);
// textToBePresentInElement 메서드로 대기 조건 설정
w.until(ExpectedConditions.textToBePresentInElement(By.xpath("//img[@title='Whiteboard']"),"Whiteboard"));
driver.quit();
}
}정리
- 명시적 대기는 특정 요소와 조건에 맞게 동작하는 동적 대기 방식이다.
- 조건이 만족되면 설정된 최대 시간과 관계없이 즉시 다음 단계로 진행된다.
- 구현은 복잡하지만 실행 속도 저하 없이 정밀한 제어가 가능하다.
- 최대 대기 시간 초과 시
ElementNotVisibleException이 발생한다.