본문 바로가기

Programmer/JAVA

Java Selenium 파일 업로드 자동화 예제

개발작업을 하면서 테스트용 데이터가 자주 필요했다.
특히 이미지 파일을 여러 화면에 반복해서 업로드해야 하는 경우가 많았는데,
매번 직접 업로드하다 보니 시간이 꽤 걸렸다.

그래서 이 작업을 자동화할 방법이 없을까 고민하다가
Selenium을 이용해 파일 업로드를 자동으로 처리해보게 되었다.

이번 글에서는
Spring Controller에서 Selenium을 실행해 파일 업로드 작업을 자동화했던 방법
간단한 예제로 정리해본다.


개발 환경

항목내용
Java 11 이상
Spring MVC
Selenium 4.26.0
Chrome 최신 버전
Driver WebDriverManager 사용

Selenium 의존성 추가 (Maven)

Maven 프로젝트 기준으로 Selenium 의존성을 추가한다.

 
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.26.0</version>
</dependency>
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.9.2</version>
</dependency>

Spring Controller에서 Selenium 실행하기

Controller에서 Selenium을 직접 실행하는 구조로 구성했다.
관리자 페이지에서 필요할 때 바로 실행할 수 있어 편했다.

@GetMapping("/selenium")
public String runSeleniumTest() throws Exception {

    // 크롬 드라이버 버전 관리를 자동으로 처리
    WebDriverManager.chromedriver().setup();

    ChromeOptions options = new ChromeOptions();
    WebDriver driver = new ChromeDriver(options);
    driver.manage().window().maximize(); // 화면 요소 가림 방지, 브라우저 최대화

    try {
        uploadImage(driver); // 파일 업로드 자동화
    } finally {
        driver.quit(); // 실패하더라도 브라우저는 정리
    }

    return "test/result";
}

Selenium 파일 업로드 자동화

파일 업로드는 OS 파일 선택창을 띄우는 방식이 아니라,
input[type="file"] 요소에 파일 경로를 직접 전달하는 방식으로 처리한다.

private void uploadImage(WebDriver driver) {

    // 페이지 로딩 타이밍 문제를 피하기 위해 명시적 대기 사용
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

    // 파일 선택창을 띄우지 않고 input[type=file]에 직접 경로 전달
    WebElement fileInput = wait.until(
        ExpectedConditions.presenceOfElementLocated(
            By.cssSelector("input[type='file']")
        )
    );

    // 테스트용 로컬 이미지 경로
    String filePath = "C:/test/image/sample.jpg";

    // sendKeys로 파일 경로를 넘기면 업로드가 바로 시작된다
    fileInput.sendKeys(filePath);

    // 업로드 중 표시되는 로딩이 사라질 때까지 대기
    wait.until(ExpectedConditions.invisibilityOfElementLocated(
        By.id("loading")
    ));
}

마무리

Selenium은 테스트 자동화뿐 아니라
사내 SW 개발 과정에서 반복 작업을 줄이는 용도로도 충분히 활용할 수 있다.

 

특히 파일 업로드처럼
사람 손으로 반복하기 번거로운 작업을 자동화하는 데 효과적이었다.