首页 > 解决方案 > 在 C# 中使用 Selenium 添加功能的正确方法是什么?

问题描述

我正在使用 C# 中的 Selenium (4.0-rc1) 并想使用 SauceLabs,要使用此服务,我需要传递自定义功能。

在示例中,它显示了向集合添加功能(“字符串”、“字符串”),并且看起来在 Java 代码中这是正确的方法,但在 C# Selenium 实现中,此接口 ICapabilities 是只读的。

接口 ICapabilities 似乎是 DriverOptions.ToCapabilities() 的正确方法,我已经实现了一个自定义 ICapabilities,但这会生成一个空引用。在远程驱动程序中查看代码似乎立即将 ICapabilities 转换为我无法实现的内部接口 IHasCapabilitiesDictionary[1],我认为这导致我的自定义 ICapabilities 抛出空引用。

我一定错过了一些简单的东西,因为这似乎是一个常见的要求——如何将自定义功能添加到 ICapabilities 集合中。

编辑

另一个注意事项我已经尝试过已弃用的 DriverOptions.AddAdditionaCapability(name,value),即使它已经过时只是为了查看它是否有效但它会引发错误无法解析功能,因为它不将自定义功能识别为 MSEdge 选项班承认。

提前致谢。

[1] https://github.com/SeleniumHQ/selenium/blob/d6bb232e525571b334325ed0859e2168e10f6edb/dotnet/src/webdriver/WebDriver.cs

标签: c#seleniumsaucelabs

解决方案


这是对 Sauce 的有效 W3C 测试

        [TestMethod]
        public void EdgeW3C()
        {
            //TODO please set your Sauce Labs username/access key in an environment variable
            _sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME");
            // Do NOT use EnvironmentVariableTarget as it won't work in CI
            _sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY");
            _sauceOptions = new Dictionary<string, object>
            {
                ["username"] = _sauceUserName,
                ["accessKey"] = _sauceAccessKey,
                ["name"] = TestContext.TestName
            };

            var browserOptions = new EdgeOptions
            {
                BrowserVersion = "latest",
                PlatformName = "Windows 10"
                //AcceptInsecureCertificates = true //Insecure Certs are Not supported by Edge
            };

            browserOptions.AddAdditionalOption("sauce:options", _sauceOptions);

            _driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), browserOptions.ToCapabilities(),
                TimeSpan.FromSeconds(30));
            _driver.Navigate().GoToUrl("https://www.saucedemo.com");

            var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(6));
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#user-name")));
        }

您可以下载此 repo 并尝试一下


推荐阅读