Fluent Wait의 개념
Fluent Wait는 Selenium에서 제공하는 동적 대기(Dynamic Wait) 방식입니다. 드라이버가 특정 조건이 충족될 때까지 일시 정지하며, 예외를 발생시키기 전에 설정된 주기마다 조건을 반복해서 확인합니다.
일반적인 대기와 달리, Fluent Wait는 요소를 DOM에서 지속적으로 검색하지 않고 일정한 시간 간격(폴링 주기)으로 검색한다는 점이 특징입니다.
예를 들어 대기 시간이 5초로 설정된 경우, Fluent Wait는 그 5초 동안 정해진 폴링 간격마다 DOM을 모니터링합니다. 또한 Fluent Wait에서는 개발자가 조건 기반의 사용자 정의 대기 로직을 직접 구현할 수 있어 유연성이 뛰어납니다.
Fluent Wait의 핵심 구성 요소
- withTimeout(): 요소를 기다릴 최대 대기 시간을 설정합니다.
- pollingEvery(): DOM을 확인할 폴링 주기를 설정합니다.
- ignoring(): 대기 중 무시할 예외(예: NoSuchElementException)를 지정합니다.
구문(Syntax)
Wait<WebDriver> w = new FluentWait<WebDriver>(driver) .withTimeout(10, SECONDS) .pollingEvery(2, SECONDS) .ignoring(NoSuchElementException.class)
위 구문은 다음과 같이 해석할 수 있습니다.
- 최대 10초까지 대기하고,
- 2초 간격으로 조건을 확인하며,
- 그동안 발생하는 NoSuchElementException은 무시합니다.
실전 예제
아래 코드는 ChromeDriver를 사용하여 페이지에 접속한 후, 암묵적 대기(Implicit Wait)와 함께 Fluent Wait를 선언하고 사용자 정의 조건을 적용하는 전체 예제입니다.
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;
import org.openqa.selenium.support.ui.FluentWait;
public class Fluentwt {
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();
// Fluent Wait 선언
Wait<WebDriver> w = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(3))
.ignoring(NoSuchElementException.class);
WebElement fl = w.until(new Function<WebDriver, WebElement>() {
// Fluent Wait를 위한 사용자 정의 조건
public WebElement apply(WebDriver driver) {
if (driver.findElement(By.xpath("//img[@title='Whiteboard']"))
.isDisplayed()) {
return true;
} else {
return null;
}
}
});
driver.quit();
}
}코드 설명
- implicitlyWait(12, TimeUnit.SECONDS): 모든 요소 조회에 12초의 암묵적 대기를 적용합니다.
- withTimeout(Duration.ofSeconds(30)): 최대 30초까지 대기합니다.
- pollingEvery(Duration.ofSeconds(3)): 3초마다 조건을 확인합니다.
- w.until(...): Function 인터페이스를 구현하여 'Whiteboard' 이미지가 화면에 표시될 때까지 반복 확인하는 사용자 정의 조건을 작성합니다.
이처럼 Fluent Wait를 활용하면 고정된 대기 시간에 의존하지 않고, 실제 조건 충족 여부에 따라 효율적으로 대기할 수 있어 테스트 안정성과 실행 속도를 모두 향상시킬 수 있습니다.