환경 준비
- 개발 언어: Java
- JDK 버전: 17
- Maven 버전: 3.6.1
기능 개요 본 예제는 Java에서 Selenium을 사용하여 간단한 웹 자동화 작업을 수행하는 방법을 설명합니다. 주요 동작은 다음과 같습니다:
- Chrome 브라우저를 시작하고 특정 웹 페이지에 접속
- 입력 필드에 텍스트 입력
- 제출 버튼 클릭
- 결과 메시지 확인 후 브라우저 종료
프로젝트 구성
pom.xml 설정
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
</parent>
<groupId>com.fhh.selenium</groupId>
<artifactId>demo</artifactId>
<version>1.0.0</version>
<name>SeleniumAutomationDemo</name>
<description>Automated browser testing with Selenium in Java</description>
<properties>
<java.version>17</java.version>
<selenium.version>4.23.1</selenium.version>
<webdrivermanager.version>5.9.2</webdrivermanager.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Selenium Core -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<!-- WebDriver Manager (자동 드라이버 관리) -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
브라우저 조작 클래스: WebAutomation.java
package com.fhh.selenium;
import lombok.AllArgsConstructor;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.function.Consumer;
@AllArgsConstructor
public class WebAutomation {
private final WebDriver driver;
public WebAutomation navigateTo(String url) {
driver.get(url);
return this;
}
public WebAutomation captureTitle(Consumer<String> callback) {
callback.accept(driver.getTitle());
return this;
}
public WebAutomation enterText(String fieldName, String value) {
WebElement inputField = driver.findElement(By.name(fieldName));
inputField.clear();
inputField.sendKeys(value);
return this;
}
public WebAutomation submitForm() {
WebElement submitBtn = driver.findElement(By.cssSelector("button"));
submitBtn.click();
return this;
}
public WebAutomation verifyMessage(Consumer<String> callback) {
WebElement resultElement = driver.findElement(By.id("message"));
callback.accept(resultElement.getText());
return this;
}
public void closeBrowser() {
driver.quit();
}
}
사용자 행동 추상화: UserInteraction.java
package com.fhh.selenium;
import lombok.AllArgsConstructor;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
@AllArgsConstructor
public class UserInteraction {
private final WebDriver driver;
public UserInteraction authenticate(String username, String password) {
WebElement userField = driver.findElement(By.id("username"));
userField.clear();
userField.sendKeys(username);
WebElement passField = driver.findElement(By.id("password"));
passField.clear();
passField.sendKeys(password);
driver.findElement(By.id("submit")).click();
return this;
}
public UserInteraction signOut() {
WebElement logoutBtn = driver.findElement(By.id("log-out"));
logoutBtn.click();
return this;
}
}
테스트 실행 클래스: AutomationTest.java
package com.fhh.selenium;
import org.junit.jupiter.api.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AutomationTest {
private WebDriver browser;
@BeforeEach
void setUp() {
browser = new ChromeDriver();
browser.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}
@Test
void testWebFormSubmission() {
// 1. 페이지 이동
browser.get("https://www.selenium.dev/selenium/web/web-form.html");
// 2. 제목 검증
String pageTitle = browser.getTitle();
assertEquals("Web form", pageTitle);
// 3. 입력 필드에 값 입력
browser.findElement(By.name("my-text")).sendKeys("Test selenium");
// 4. 제출 버튼 클릭
browser.findElement(By.cssSelector("button")).click();
// 5. 이동된 페이지의 제목 확인
assertEquals("Web form - target page", browser.getTitle());
// 6. 결과 메시지 검증
String message = browser.findElement(By.id("message")).getText();
assertEquals("Received!", message);
}
@Test
void testWithChainedActions() {
new WebAutomation(browser)
.navigateTo("https://www.selenium.dev/selenium/web/web-form.html")
.captureTitle(title -> assertEquals("Web form", title))
.enterText("my-text", "Test selenium")
.submitForm()
.captureTitle(title -> assertEquals("Web form - target page", title))
.verifyMessage(msg -> assertEquals("Received!", msg))
.closeBrowser();
}
@AfterEach
void tearDown() {
if (browser != null) {
browser.quit();
}
}
}
실행 결과 테스트가 실행되면, 시스템이 자동으로 Chrome 브라우저를 열고 지정된 웹 페이지에 접근합니다. 이후 입력란에 텍스트를 입력하고 제출 버튼을 클릭하며, 페이지 전환 후 결과 메시지를 확인한 후 브라우저를 종료합니다. 전체 과정은 약 1~5초 내외로 완료되며, 성공 여부는 테스트 결과로 확인됩니다.
이 방식은 반복적인 웹 작업 자동화, 품질 보증, 회귀 테스트 등에 유용하게 활용할 수 있습니다.