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

如何为Java TestNG框架配置SauceLabs自动化测试环境

Java TestNG 框架配置 SauceLabs 正确方案

现有配置的问题修正点

  • sauce:options 配置项错误传入了字符串sauceOpts,需直接传入你创建的MutableCapabilities类型的sauceOpts对象,不需要包裹引号
  • 认证参数键名错误,SauceLabs要求的访问密钥字段为accessKey(K大写),小写accesskey会触发认证失败
  • platformName配置值windows 10存在多余空格,正确取值为Windows 10(首字母大写,中间仅保留1个空格)
  • 类名拼写错误,Webdriver正确拼写为WebDriver
  • driver变量定义在@BeforeClass方法内部属于局部变量,后续测试用例方法无法调用该实例

完整可运行配置示例

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;

public class SauceLabsTest {
    private WebDriver driver;

    @BeforeClass
    public void init() throws MalformedURLException {
        MutableCapabilities sauceOpts = new MutableCapabilities();
        sauceOpts.setCapability("username", "替换为你自己的用户名");
        sauceOpts.setCapability("accessKey", "替换为你自己的访问密钥");
        // 可选配置:测试用例名称、构建号等,方便在SauceLabs仪表盘筛选
        sauceOpts.setCapability("name", "TestNG测试用例");

        ChromeOptions options = new ChromeOptions();
        options.setCapability("sauce:options", sauceOpts);
        options.setCapability("browserVersion", "latest");
        options.setCapability("platformName", "Windows 10");

        driver = new RemoteWebDriver(new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub"), options);
    }

    @Test
    public void sampleTest() {
        driver.get("https://www.baidu.com");
        Assert.assertEquals(driver.getTitle(), "百度一下,你就知道");
    }

    @AfterClass
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

如果需要将测试结果同步到SauceLabs仪表盘,可新增@AfterMethod配置自动上报用例执行状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:48:03