Testing with Selenium
此文档概述了使用 Selenium 测试 webforJ 应用程序的过程,特别是聚焦于来自 webforj-archetype-hello-world 的 HelloWorldView。
应用基础
要了解更多关于 webforj-archetype-hello-world 的信息,请参阅 应用基础介绍 部分。
先决条件
在运行 Selenium 测试之前,请确保以下事项:
- webforJ 应用程序已正确设置并在您的本地服务器上运行。
- 您已安装:
- Selenium Java 绑定。
- 适用于您的浏览器的 WebDriver。
- 用于项目依赖的 Maven。
Maven 配置
在您的 pom.xml 中添加 Selenium 和其他测试库所需的依赖:
pom.xml
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.27.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.9.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
测试示例:HelloWorldView
以下代码演示了针对 HelloWorldView 组件的基于 Selenium 的测试。
HelloWorldViewTest.java
package com.example.views;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static java.time.Duration.ofSeconds;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import io.github.bonigarcia.wdm.WebDriverManager;
class HelloWorldViewTest {
private WebDriver driver;
private static final String PORT = System.getProperty("server.port", "8080");
@BeforeAll
static void setupAll() {
WebDriverManager.chromedriver().setup();
}
@BeforeEach
void setup() {
driver = new ChromeDriver();
driver.get("http://localhost:" + PORT + "/");
new WebDriverWait(driver, ofSeconds(30))
.until(titleIs("webforJ Hello World"));
}
@AfterEach
void teardown() {
if (driver != null) {
driver.quit();
}
}
@Test
void shouldClickButton() {
WebElement button = driver.findElement(By.tagName("dwc-button"));
assertEquals("Say Hello", button.getText(), "Button text mismatch!");
}
}
关键步骤
-
初始化 WebDriver:
- 使用
WebDriverManager自动管理浏览器的驱动程序可执行文件。
- 使用
-
设置测试环境:
- 在
http://localhost:<port>/启动测试服务器。 - 等待页面标题与预期的
webforJ Hello World匹配。
- 在
-
与元素交互:
- 使用
By.tagName
- 使用