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

Spring Boot集成测试:如何在Serenity.conf配置Remote Chrome Capabilities?

问题描述

尝试使用远程Selenium Chrome Driver执行Spring Boot集成测试,当前serenity.conf配置如下:

webdriver {
  driver = "remote"
  remote {
      url="http://localhost:4444/wd/hub"
      driver=chrome
  }
}

执行测试时访问本地Spring Boot服务(通过@LocalServerPort获取端口)出现ERR_CONN_REFUSED错误,但访问外部网站(如Google)正常。推测缺少remote-allow-origins=* Chrome Capability,尝试在remote节点下添加如下配置后仍无效果:

capabilities {
      "goog:chromeOptions" {
        args = [
        "start-maximized",
        "headless",
        "remote-allow-origins=*",
        "test-type",
        "no-sandbox",
        "ignore-certificate-errors",
        "disable-popup-blocking",
        "version",
        "disable-infobars",
        "disable-extensions",
        "disable-gpu"
        ]
      }

测试代码片段:

@Managed(driver = "remote")
private WebDriver webDriver;

@LocalServerPort
private int serverPort;

@Test
void pageLoads() {
    webDriver.get("http://" + "localhost" + ":" + serverPort);
    // ...其他测试逻辑
}

使用嵌入式Chrome时测试可正常运行,询问是否可通过serenity.conf添加所需Capabilities及解决方法。

解决方案

1. 确认Serenity Capabilities的正确配置格式

Serenity的远程驱动Capabilities配置需放在webdriver.remote节点下,你的配置结构正确,但需修正语法错误并移除无效参数。完整正确配置示例:

webdriver {
  driver = "remote"
  remote {
      url="http://localhost:4444/wd/hub"
      driver=chrome
      capabilities {
        "goog:chromeOptions" {
          args = [
            "start-maximized",
            "headless",
            "remote-allow-origins=*",
            "test-type",
            "no-sandbox",
            "ignore-certificate-errors",
            "disable-popup-blocking",
            "disable-infobars",
            "disable-extensions",
            "disable-gpu"
          ]
        }
      }
  }
}

注:移除了无效的version参数,该参数不属于Chrome启动参数列表。

2. 解决本地服务访问的核心问题

访问外部网站正常但本地服务拒绝连接,核心原因是远程Chrome Driver运行环境中的localhost指向Driver所在的容器/机器,而非Spring Boot服务所在的宿主机器。

解决方法:

  • 若远程Driver运行在Docker容器中:将访问地址改为宿主机器的局域网IP(如http://192.168.x.x:${serverPort}),而非localhost。
  • 若Driver和Spring Boot服务在同一机器但隔离环境:确保Spring Boot服务绑定到0.0.0.0(默认已绑定,若有自定义配置需检查),再用宿主IP访问。

修改测试代码中的地址:

// 获取宿主机器局域网IP
String hostIp = InetAddress.getLocalHost().getHostAddress();
webDriver.get("http://" + hostIp + ":" + serverPort);

3. 验证Capabilities是否生效

可通过打印Driver的Capabilities确认配置是否加载:

@Test
void pageLoads() {
    ChromeOptions options = (ChromeOptions) ((RemoteWebDriver) webDriver).getCapabilities().getCapability("goog:chromeOptions");
    System.out.println("已加载的Chrome启动参数: " + options.getArguments());
    // 后续访问逻辑
}

若输出包含remote-allow-origins=*,说明Capabilities配置生效,此时问题大概率是本地服务的访问地址问题。

4. 其他排查点

  • 检查Spring Boot服务日志,确认服务确实启动在serverPort指定的端口。
  • 确认宿主机器防火墙未阻止serverPort的入站请求。
  • 若使用Docker运行Selenium Grid,确保容器与宿主机器在同一网络,或端口映射配置正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:43:16