65.9K
CodeProject 正在变化。 阅读更多。
Home

10 个高级 WebDriver 技巧和窍门 - 第 3 部分

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3投票s)

2016年2月28日

Ms-PL

3分钟阅读

viewsIcon

12259

查找一些高级 WebDriver 技巧与窍门,了解如何使用该框架来处理扩展或下载文件。文章 10 个高级 WebDriver 技巧与窍门 第 3 部分 首先出现在 Automate The Planet 上。

引言

您可能知道,我正在开发一个名为 使用 WebDriver 进行务实的自动化 的系列文章。它们包含大量关于如何使用 WebDriver 开始编写自动化测试的实用信息。此外,它们还包含许多更高级的主题,例如自动化策略、基准和研究。在接下来的几篇文章中,我将与您分享一些高级 WebDriver 在测试中的用法。事不宜迟,以下是今天的高级 WebDriver 自动化技巧与窍门。

1. 启动带有插件的 FirefoxDriver

只需使用 FirefoxProfile 类的 AddExtension 加载所需的扩展即可。

FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"C:\extensionsLocation\extension.xpi");
IWebDriver driver = new FirefoxDriver(profile);

2. 设置 HTTP 代理 ChromeDriver

ChromeDriver 配置代理与为 FirefoxDriver 配置代理略有不同。您需要将特殊的 Proxy 类与 ChromeOptions 结合使用。

ChromeOptions options = new ChromeOptions();
var proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3239";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);

Digital security finger print scan in blue and black

3. 设置带有身份验证的 HTTP 代理 ChromeDriver

与前一个示例的唯一区别是 --proxy-server 参数的配置。

ChromeOptions options = new ChromeOptions();
var proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3239";
options.Proxy = proxy;
options.AddArguments("--proxy-server=http://user:password@127.0.0.1:3239");
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);

4. 启动带有未打包扩展的 ChromeDriver

Chrome 扩展可以是已打包或未打包的。打包的扩展是带有 .crx 扩展名的单个文件。未打包的扩展是一个包含扩展的目录,包括一个 manifest.json 文件。要加载未打包的扩展,您需要设置 load-extension 参数。

ChromeOptions options = new ChromeOptions();
options.AddArguments("load-extension=/pathTo/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);

Create Jenkins Job for Creating NuGet Packages

5. 启动带有打包扩展的 ChromeDriver

您需要使用 ChromeOptions 类的 AddExtension 方法来设置打包扩展的路径,而不是设置 load-extension 参数。

ChromeOptions options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("local/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);

6. 断言按钮已启用或已禁用

您可以通过 IWebElement 接口的 Enabled 属性检查元素是否已禁用。

[TestMethod]
public void AssertButtonEnabledDisabled()
{
    this.driver.Navigate().GoToUrl
	(@"https://w3schools.org.cn/tags/tryit.asp?filename=tryhtml_button_disabled");
    this.driver.SwitchTo().Frame("iframeResult");
    IWebElement button = driver.FindElement(By.XPath("/html/body/button"));
    Assert.IsFalse(button.Enabled);
}

7. 设置和断言隐藏字段的值

您可以通过 GetAttribute 方法获取隐藏字段的值,该方法是 IWebElement 接口的一部分。获取元素的 value 属性。您可以使用一小段 JavaScript 代码来设置相同的属性。

[TestMethod]
public void AssertButtonEnabledDisabled()
{
    this.driver.Navigate().GoToUrl
	(@"https://w3schools.org.cn/tags/tryit.asp?filename=tryhtml_button_disabled");
    this.driver.SwitchTo().Frame("iframeResult");
    IWebElement button = driver.FindElement(By.XPath("/html/body/button"));
    Assert.IsFalse(button.Enabled);
}

8. 等待 AJAX 调用使用 JQuery 完成

jQuery.active 是 JQuery 在内部用于跟踪并发 AJAX 请求数量的变量。等待 jQuery.active 的值为零。然后,继续执行下一个操作。

public void WaitForAjaxComplete(int maxSeconds)
{
    bool isAjaxCallComplete = false;
    for (int i = 1; i <= maxSeconds; i++)
    {
        isAjaxCallComplete = (bool)((IJavaScriptExecutor)driver).
        ExecuteScript("return window.jQuery != undefined && jQuery.active == 0");

        if (isAjaxCallComplete)
        {
            return;
        }
        Thread.Sleep(1000);
    }
    throw new Exception(string.Format("Timed out after {0} seconds", maxSeconds));
}

Download File

9. 验证文件已下载 ChromeDriver

要更改当前 Chrome 实例的默认下载目录,请设置 download.default_directory 参数。当我们启动文件下载时,我们使用 WebDriverWait 等待文件在文件系统上存在。最后,我们断言文件大小。整个代码被 try-finally 块包围。在 finally 中,我们删除下载的文件,以便我们的测试每次都保持一致。

[TestMethod]
public void VerifyFileDownloadChrome()
{
    string expectedFilePath = 
    @"c:\temp\Testing_Framework_2015_3_1314_2_Free.exe";
    try
    {
        String downloadFolderPath = @"c:\temp\";
        var options = new ChromeOptions();
        options.AddUserProfilePreference
        ("download.default_directory", downloadFolderPath);
        driver = new ChromeDriver(options);

        driver.Navigate().GoToUrl
        ("https://www.telerik.com/download-trial-file/v2/telerik-testing-framework");
        WebDriverWait wait = 
        new WebDriverWait(driver, TimeSpan.FromSeconds(30));
        wait.Until((x) =>
        {
            return File.Exists(expectedFilePath);
        });
        FileInfo fileInfo = new FileInfo(expectedFilePath);
        long fileSize = fileInfo.Length;
        Assert.AreEqual(4326192, fileSize);
    }
    finally
    {
        if (File.Exists(expectedFilePath))
        {
            File.Delete(expectedFilePath);
        }
    }
}

10. 验证文件已下载 FirefoxDriver

FirefoxDriver 的代码与 ChromeDriver 的代码类似。我们需要设置一些参数,以便浏览器不会每次都询问我们将指定的文件保存在哪里。

[TestMethod]
public void VerifyFileDownloadFirefox()
{
    string expectedFilePath = @"c:\temp\Testing_Framework_2015_3_1314_2_Free.exe";
    try
    {
        String downloadFolderPath = @"c:\temp\";
        FirefoxProfile profile = new FirefoxProfile();
        profile.SetPreference("browser.download.folderList", 2);
        profile.SetPreference("browser.download.dir", downloadFolderPath);
        profile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", 
        "application/msword, application/binary, application/ris, text/csv, 
        image/png, application/pdf, text/html, text/plain, application/zip, 
        application/x-zip, application/x-zip-compressed, 
        application/download, application/octet-stream");
        this.driver = new FirefoxDriver(profile);

        driver.Navigate().GoToUrl
        ("https://www.telerik.com/download-trial-file/v2/telerik-testing-framework");
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
        wait.Until((x) =>
        {
            return File.Exists(expectedFilePath);
        });
        FileInfo fileInfo = new FileInfo(expectedFilePath);
        long fileSize = fileInfo.Length;
        Assert.AreEqual(4326192, fileSize);
    }
    finally
    {
        if (File.Exists(expectedFilePath))
        {
            File.Delete(expectedFilePath);
        }
    }
}

到目前为止,'使用 WebDriver 进行务实的自动化' 系列

 

如果你喜欢我的文章,请随意订阅
另外,请点击这些分享按钮。谢谢!

源代码

文章 10 个高级 WebDriver 技巧与窍门 第 3 部分 首先出现在 Automate The Planet 上。

所有图片均从 DepositPhotos.com购买,不能免费下载和使用。
许可协议

© . All rights reserved.