Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
解决Selenium测试中WebSocket服务器端口冲突导致的并发失败问题_创想鸟

解决Selenium测试中WebSocket服务器端口冲突导致的并发失败问题

解决Selenium测试中WebSocket服务器端口冲突导致的并发失败问题

在使用selenium测试基于websocket的应用时,如果多个测试用例并发运行,可能会遇到单个测试通过但整体失败的情况,表现为后续测试无法与websocket服务器建立连接,导致元素不可交互。这通常是由于websocket服务器在测试用例之间未正确关闭,导致端口被占用。本文将详细分析该问题,并提供在测试结束时优雅关闭websocket服务器的解决方案。

问题描述:Selenium与WebSocket测试的并发挑战

在自动化测试基于WebSocket的Web应用时,我们可能会遇到一个常见但棘手的问题:当单独运行每个测试用例时,它们都能成功通过;然而,一旦将多个测试用例一起运行,除了第一个测试外,后续的测试往往会失败。

具体的失败表现通常是:

元素不可交互异常: Selenium抛出 org.openqa.selenium.ElementNotInteractableException 异常,例如在尝试点击一个按钮时。页面元素状态异常: 页面上的关键元素(如本例中的 startButton)未能按预期加载或显示,这通常意味着客户端的WebSocket连接未能成功建立。服务器启动日志异常: 在服务器端,可能只会在第一个测试用例启动时打印“Server started!”信息,后续测试尝试启动服务器时没有相关日志输出。

这种现象强烈暗示了资源冲突,特别是网络端口的占用问题。

测试环境概述

为了更好地理解问题,我们先审视一下典型的测试环境配置

客户端HTML页面

客户端是一个简单的HTML页面,通过JavaScript创建WebSocket连接到 ws://localhost:8800。连接成功后,页面上的 startButton 可能会根据WebSocket的状态进行交互。

        something
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); }

Java WebSocket服务器

服务器端使用 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事件处理方法 ...}

Selenium测试框架配置

测试使用JUnit 5框架,通过 WebDriverManager 管理ChromeDriver,并在每个测试用例前后执行设置和清理操作。

闪念贝壳 闪念贝壳

闪念贝壳是一款AI 驱动的智能语音笔记,随时随地用语音记录你的每一个想法。

闪念贝壳 218 查看详情 闪念贝壳

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生命周期:

@BeforeEach 方法会在每个 @Test 方法执行前运行一次。在 setup() 方法中,我们每次都会创建一个新的 Server 实例并调用 server.start() 来启动它,使其监听8800端口。@AfterEach 方法会在每个 @Test 方法执行后运行一次。在原始的 teardown() 方法中,我们只调用了 driver.quit() 来关闭Selenium WebDriver实例。

端口占用问题:

当第一个测试用例 (testWebSocketConnectionAndClick) 执行完毕后,其 teardown() 方法被调用,WebDriver被关闭。然而,由该测试用例在 setup() 中启动的 WebSocketServer 实例并没有被显式关闭。尽管JVM进程可能仍在运行,但该 WebSocketServer 实例会继续占用8800端口。当第二个测试用例 (anotherWebSocketTest) 开始执行时,它的 setup() 方法会再次被调用。它会尝试在8800端口上启动一个新的 WebSocketServer 实例。由于8800端口已经被第一个测试用例的服务器实例占用,第二个服务器实例的启动会静默失败或抛出异常但未被捕获。Server.onStart() 方法中的 “Server started!” 日志因此不会被打印。客户端HTML页面尝试连接 ws://localhost:8800 时,由于没有可用的WebSocket服务器响应,连接会失败。客户端的JavaScript代码(例如,在 webSocket.onopen 中改变 startButton 的 visibility 或 disabled 属性)将不会执行,导致Selenium在尝试点击 startButton 时,该元素仍然处于不可交互的状态,从而抛出 ElementNotInteractableException。

通过创建一个新的HTML页面和服务器实例,并让它们监听不同的端口(例如8802),如果此时测试通过,则进一步证实了端口冲突是问题的根本原因。

解决方案:在测试后关闭WebSocket服务器

解决此问题的核心在于确保在每个测试用例结束后,所有由该测试用例启动的资源都被正确释放,特别是网络端口。我们需要在 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; // 导入IOExceptionimport java.nio.file.Path;import java.nio.file.Paths;import java.time.Duration; // 导入Durationimport org.openqa.selenium.support.ui.WebDriverWait; // 导入WebDriverWaitimport org.openqa.selenium.support.ui.ExpectedConditions; // 导入ExpectedConditionsimport org.openqa.selenium.By; // 导入Bypublic 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)来等待元素满足特定条件(例如,变为可点击状态)后再进行操作。

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));wait.until(ExpectedConditions.elementToBeClickable(By.id(“startButton”)));这比简单的 Thread.sleep() 更健壮,因为它会等待条件满足,而不是固定等待一段时间,从而提高测试效率和稳定性。

服务器启动后的短暂等待:尽管在 teardown 中关闭了服务器,但在 setup 中启动服务器后,仍可能需要一个短暂的延迟,以确保服务器完全启动并开始监听端口,然后再让客户端尝试连接。这里示例中使用了 Thread.sleep(500),但在生产级别的测试中,可以考虑更复杂的机制,例如检查服务器日志或尝试连接直到成功。

总结

当Selenium测试与WebSocket服务器结合时,如果多个测试用例并发运行失败,通常是由于WebSocket服务器实例在测试之间未正确关闭,导致网络端口被占用。解决此问题的关键在于在每个测试用例的清理阶段(JUnit的 @AfterEach 方法)显式地停止WebSocket服务器,释放其占用的端口。同时,结合Selenium的显式等待机制来处理WebSocket连接的异步性,可以显著提高自动化测试的稳定性和可靠性。良好的资源管理和测试隔离性是编写健壮、可维护自动化测试套件的基石。

以上就是解决Selenium测试中WebSocket服务器端口冲突导致的并发失败问题的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/987321.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
CSS工具Autoprefixer如何使用_自动添加浏览器前缀技巧
上一篇 2025年12月1日 21:05:47
EasyTier异地组网怎么用
下一篇 2025年12月1日 21:05:54

相关推荐

发表回复

登录后才能评论
关注微信