You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Cucumber与Java的Selenium Grid Hub和Node配置实现求助

适配Selenium Grid Hub & Node到你的BDD测试框架

我来帮你把现有代码调整为连接Selenium Grid的模式,同时补充Hub和Node的部署配置要点,这样你的Cucumber+Java+Selenium BDD框架就能实现分布式测试执行了:

1. 修改WebDriver初始化代码

你当前的代码是直接启动本地ChromeDriver,现在需要替换为连接远程Grid Hub的RemoteWebDriver,同时保留原有的Chrome配置。修改后的代码如下:

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.JavascriptExecutor;
import com.paulhammant.ngwebdriver.NgWebDriver;

// 你的驱动初始化逻辑
System.setProperty("webdriver.chrome.driver", driversBasePath + "\\chromedriver.exe"); 
Map<String, Object> prefs = new HashMap<String, Object>(); 
ChromeOptions options = new ChromeOptions(); 
options.setExperimentalOption("prefs", prefs); 

// 连接到Selenium Grid Hub
try {
    dr = new RemoteWebDriver(new URL("http://192.234.51.62:4444/wd/hub"), options);
} catch (MalformedURLException e) {
    e.printStackTrace();
    // 可根据框架需求自定义异常处理,比如抛出测试失败的RuntimeException
    throw new RuntimeException("Failed to connect to Selenium Grid Hub", e);
}

// 后续的Angular等待、Actions、WebDriverWait等初始化保持不变
NgWebDriver ngWebDriver = new NgWebDriver((JavascriptExecutor) dr); 
ngWebDriver.waitForAngularRequestsToFinish(); 
ac = new Actions(dr); 
wdw = new WebDriverWait(dr, 30); 
js = (JavascriptExecutor) dr; 
dr.get("https://www.google.com"); // 注意添加HTTP/HTTPS协议,避免URL解析错误

关键修改点:

  • 新增导入java.net.URL和java.net.MalformedURLException类,用于处理Hub地址的URL解析
  • 将new ChromeDriver(options)替换为new RemoteWebDriver(HubURL, options),实现远程连接
  • 修复了dr.get中的URL,补充https://协议头,避免WebDriver无法定位资源的问题

2. Node节点的部署与启动

如果还未配置Grid Node节点,需要在目标机器上完成以下操作:

  • 确保Node机器安装了与Hub同版本的Selenium Server、对应版本的Chrome浏览器和chromedriver
  • 下载Selenium Server Jar包(建议使用与你当前Selenium依赖一致的版本)
  • 在Node机器上执行启动命令:
java -jar selenium-server-4.x.x.jar node --hub http://192.234.51.62:4444/wd/hub --port 5555 --browser "browserName=chrome,maxInstances=5,platform=WINDOWS"

命令参数说明:

  • --hub:指定Grid Hub的地址,与你的Hub地址保持一致
  • --port:设置Node节点的监听端口,默认5555,可根据需要修改
  • --browser:配置Node支持的浏览器信息,包括浏览器名称、最大并发实例数、操作系统平台等,可根据你的测试需求调整

3. 验证Grid连接状态

你可以通过访问Hub的控制台页面(http://192.234.51.62:4444/ui)查看已注册的Node节点信息,确认节点成功上线后,运行你的BDD测试即可看到测试任务被分配到Grid节点上执行。

内容的提问来源于stack exchange,提问作者RJM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:12:35