
在使用selenium测试基于websocket的应用时,如果多个测试用例并发运行,可能会遇到单个测试通过但整体失败的情况,表现为后续测试无法与websocket服务器建立连接,导致元素不可交互。这通常是由于websocket服务器在测试用例之间未正确关闭,导致端口被占用。本文将详细分析该问题,并提供在测试结束时优雅关闭websocket服务器的解决方案。
在自动化测试基于WebSocket的Web应用时,我们可能会遇到一个常见但棘手的问题:当单独运行每个测试用例时,它们都能成功通过;然而,一旦将多个测试用例一起运行,除了第一个测试外,后续的测试往往会失败。
具体的失败表现通常是:
这种现象强烈暗示了资源冲突,特别是网络端口的占用问题。
为了更好地理解问题,我们先审视一下典型的测试环境配置:
客户端是一个简单的HTML页面,通过JavaScript创建WebSocket连接到 ws://localhost:8800。连接成功后,页面上的 startButton 可能会根据WebSocket的状态进行交互。
<html>
<head>
<meta charset="UTF-8">
<title>something</title>
</head>
<body>
<div ><button id="startButton" onclick="start()" style="visibility: hidden;">START</button></div>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8800");
var startButton = document.getElementById("startButton");
webSocket.onopen = function(event){ /* ... */ };
webSocket.onmessage = function(event){ /* ... */ };
webSocket.onclose = function(event){ /* ... */ };
webSocket.onerror = function(event){ /* ... */ };
function start(){
wsSendMessage("start,"+player_id);
startButton.innerText = "STARTED";
startButton.disabled="true";
}
function wsSendMessage(message){
webSocket.send(message);
}
</script>
</body>
</html>服务器端使用 org.java_websocket 库实现,监听特定端口(例如8800)。在服务器启动时,会打印一条日志信息。
import org.java_websocket.WebSocketServer;
import java.net.InetSocketAddress;
public class Server extends WebSocketServer {
public Server(int port) {
super(new InetSocketAddress(port));
}
@Override
public void onStart() {
System.out.println("Server started!");
setConnectionLostTimeout(0);
setConnectionLostTimeout(500);
}
// ... 其他WebSocket事件处理方法 ...
}测试使用JUnit 5框架,通过 WebDriverManager 管理ChromeDriver,并在每个测试用例前后执行设置和清理操作。
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.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MyWebSocketTests {
WebDriver driver;
Server server; // WebSocket服务器实例
Path sampleFile;
@BeforeAll
static void setupClass() {
WebDriverManager.chromedriver().setup();
}
@BeforeEach
void setup() throws InterruptedException {
driver = new ChromeDriver();
sampleFile = Paths.get("path/web.html"); // 替换为实际路径
server = new Server(8800); // 每次测试前启动WebSocket服务器
server.start();
}
@AfterEach
void teardown() throws InterruptedException {
driver.quit(); // 关闭WebDriver
// server.stop() 缺失!
}
@Test
void testWebSocketConnectionAndClick() throws InterruptedException {
driver.get(sampleFile.toUri().toString());
// 假设这里需要等待WebSocket连接建立,以及startButton可见并可点击
driver.findElement(By.id("startButton")).click();
// ... 其他操作和断言 ...
}
@Test
void anotherWebSocketTest() throws InterruptedException {
driver.get(sampleFile.toUri().toString());
// 假设这里需要等待WebSocket连接建立,以及startButton可见并可点击
driver.findElement(By.id("startButton")).click();
// ... 其他操作和断言 ...
}
}问题产生的根源在于测试用例之间的资源管理不当,具体来说是WebSocket服务器实例未能在每个测试用例结束后正确关闭。
JUnit生命周期:
端口占用问题:
通过创建一个新的HTML页面和服务器实例,并让它们监听不同的端口(例如8802),如果此时测试通过,则进一步证实了端口冲突是问题的根本原因。
解决此问题的核心在于确保在每个测试用例结束后,所有由该测试用例启动的资源都被正确释放,特别是网络端口。我们需要在 teardown() 方法中显式地关闭WebSocket服务器。
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.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException; // 导入IOException
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration; // 导入Duration
import org.openqa.selenium.support.ui.WebDriverWait; // 导入WebDriverWait
import org.openqa.selenium.support.ui.ExpectedConditions; // 导入ExpectedConditions
import org.openqa.selenium.By; // 导入By
public class MyWebSocketTests {
WebDriver driver;
Server server;
Path sampleFile;
@BeforeAll
static void setupClass() {
WebDriverManager.chromedriver().setup();
}
@BeforeEach
void setup() throws InterruptedException {
driver = new ChromeDriver();
sampleFile = Paths.get("path/web.html"); // 替换为实际路径
server = new Server(8800);
server.start();
// 确保服务器有足够时间启动并监听端口
Thread.sleep(500); // 简单的等待,生产环境建议使用更健壮的机制
}
@AfterEach
void teardown() throws InterruptedException {
if (driver != null) {
driver.quit(); // 关闭WebDriver
}
if (server != null) {
try {
server.stop(); // 停止WebSocket服务器
} catch (IOException | InterruptedException e) {
System.err.println("Error stopping WebSocket server: " + e.getMessage());
Thread.currentThread().interrupt(); // 重新设置中断状态
}
}
}
@Test
void testWebSocketConnectionAndClick() throws InterruptedException {
driver.get(sampleFile.toUri().toString());
// 使用显式等待确保WebSocket连接建立且按钮可点击
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("startButton")));
driver.findElement(By.id("startButton")).click();
// ... 其他操作和断言 ...
}
@Test
void anotherWebSocketTest() throws InterruptedException {
driver.get(sampleFile.toUri().toString());
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("startButton")));
driver.findElement(By.id("startButton")).click();
// ... 其他操作和断言 ...
}
}关键改动: 在 teardown() 方法中,我们添加了对 server.stop() 的调用,并用 try-catch 块包裹,以处理可能发生的 IOException 或 InterruptedException。这样,在每个测试用例结束后,WebSocket服务器都会被正确关闭,释放8800端口,确保下一个测试用例可以顺利启动自己的服务器实例。
资源管理的重要性: 在自动化测试中,对所有外部资源(如WebDriver实例、数据库连接、文件句柄、网络端口、模拟服务器等)的生命周期管理至关重要。任何未正确释放的资源都可能导致测试之间的互相干扰,从而产生不稳定或难以调试的失败。
测试隔离性: 每个测试用例都应该是独立的,不依赖于其他测试用例的执行顺序或状态。@BeforeEach 和 @AfterEach 方法的职责就是为每个测试提供一个干净、可预测的环境,并在测试结束后清理所有痕迹。
异常处理: 在关闭资源时,总是建议使用 try-catch 块来处理可能发生的异常。例如,server.stop() 可能会抛出 IOException 或 InterruptedException。妥善处理这些异常可以防止测试因资源关闭失败而中断,同时提供有用的错误信息。对于 InterruptedException,最佳实践是重新设置线程的中断状态。
异步操作的等待: WebSocket连接的建立是一个异步过程。客户端HTML页面在收到 onopen 事件后才会更新DOM,使 startButton 可交互。因此,在Selenium中,仅仅加载页面后立即尝试点击元素是不够的。我们应该使用Selenium的显式等待(WebDriverWait)来等待元素满足特定条件(例如,变为可点击状态)后再进行操作。
服务器启动后的短暂等待: 尽管在 teardown 中关闭了服务器,但在 setup 中启动服务器后,仍可能需要一个短暂的延迟,以确保服务器完全启动并开始监听端口,然后再让客户端尝试连接。这里示例中使用了 Thread.sleep(500),但在生产级别的测试中,可以考虑更复杂的机制,例如检查服务器日志或尝试连接直到成功。
当Selenium测试与WebSocket服务器结合时,如果多个测试用例并发运行失败,通常是由于WebSocket服务器实例在测试之间未正确关闭,导致网络端口被占用。解决此问题的关键在于在每个测试用例的清理阶段(JUnit的 @AfterEach 方法)显式地停止WebSocket服务器,释放其占用的端口。同时,结合Selenium的显式等待机制来处理WebSocket连接的异步性,可以显著提高自动化测试的稳定性和可靠性。良好的资源管理和测试隔离性是编写健壮、可维护自动化测试套件的基石。
以上就是解决Selenium测试中WebSocket服务器端口冲突导致的并发失败问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号