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

1. 拖放
您可以使用 WebDriver 的特殊 Actions 类来执行复杂的 UI 交互。通过其 DragAndDropToOffset 方法,您可以进行拖放操作。您只需要设置所需的 X 和 Y 偏移量。
[TestMethod]
public void DragAndDrop()
{
this.driver.Navigate().GoToUrl(@"http://loopj.com/jquery-simple-slider/");
IWebElement element = driver.FindElement(By.XPath("//*[@id='project']/p[1]/div/div[2]"));
Actions move = new Actions(driver);
move.DragAndDropToOffset(element, 30, 0).Perform();
}
2. 上传文件
使用 WebDriver 上传文件是一项直接的任务。您需要定位文件元素,并使用 IWebElement 的 SendKeys 方法来设置文件的路径。
[TestMethod]
public void FileUpload()
{
this.driver.Navigate().GoToUrl(
@"https://demos.telerik.com/aspnet-ajax/ajaxpanel/application-scenarios/file-upload/defaultcs.aspx");
IWebElement element =
driver.FindElement(By.Id("ctl00_ContentPlaceholder1_RadUpload1file0"));
String filePath =
@"D:\Projects\PatternsInAutomation.Tests\WebDriver.Series.Tests\bin\Debug\WebDriver.xml";
element.SendKeys(filePath);
}
3. 处理 JavaScript 弹出窗口
通过 IWebDriver 的 ITargetLocator 接口,您可以定位 JavaScript 警报。然后,您可以使用 IAlert 接口的 Accept 和 Dismiss 方法。
[TestMethod]
public void JavaScripPopUps()
{
this.driver.Navigate().GoToUrl(
@"https://w3schools.org.cn/js/tryit.asp?filename=tryjs_confirm");
this.driver.SwitchTo().Frame("iframeResult");
IWebElement button = driver.FindElement(By.XPath("/html/body/button"));
button.Click();
IAlert a = driver.SwitchTo().Alert();
if (a.Text.Equals("Press a button!"))
{
a.Accept();
}
else
{
a.Dismiss();
}
}
4. 在浏览器窗口或标签页之间切换
WebDriver 在一个浏览器窗口的范围内驱动浏览器。但是,我们可以使用其 SwitchTo 方法来更改目标窗口或标签页。
[TestMethod]
public void MovingBetweenTabs()
{
this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com/compelling-sunday-14022016/");
driver.FindElement(By.LinkText("10 Advanced WebDriver Tips and Tricks Part 1")).Click();
driver.FindElement(By.LinkText("The Ultimate Guide To Unit Testing in ASP.NET MVC")).Click();
ReadOnlyCollection<String> windowHandles = driver.WindowHandles;
String firstTab = windowHandles.First();
String lastTab = windowHandles.Last();
driver.SwitchTo().Window(lastTab);
Assert.AreEqual<string>("The Ultimate Guide To Unit Testing in ASP.NET MVC", driver.Title);
driver.SwitchTo().Window(firstTab);
Assert.AreEqual<string>("Compelling Sunday – 19 Posts on Programming and Quality Assurance", driver.Title);
}
WindowHandles 属性返回所有打开的浏览器窗口。您可以将所需标签页/窗口的名称传递给 ITargetLocator 接口(由 SwitchTo 方法返回)的 Window 方法,以更改当前目标。
5. 导航历史
WebDriver 的 INavigation 接口包含用于前进和后退的便捷方法。此外,您还可以刷新当前页面。
[TestMethod]
public void NavigationHistory()
{
this.driver.Navigate().GoToUrl(
@"https://codeproject.org.cn/Articles/1078541/Advanced-WebDriver-Tips-and-Tricks-Part");
this.driver.Navigate().GoToUrl(
@"https://codeproject.org.cn/Articles/1017816/Speed-up-Selenium-Tests-through-RAM-Facts-and-Myth");
driver.Navigate().Back();
Assert.AreEqual<string>(
"10 Advanced WebDriver Tips and Tricks - Part 1 - CodeProject",
driver.Title);
driver.Navigate().Refresh();
Assert.AreEqual<string>(
"10 Advanced WebDriver Tips and Tricks - Part 1 - CodeProject",
driver.Title);
driver.Navigate().Forward();
Assert.AreEqual<string>(
"Speed up Selenium Tests through RAM Facts and Myths - CodeProject",
driver.Title);
}
6. 更改用户代理
在我系列文章的上一篇博文中,我向您展示了如何创建一个新的自定义 Firefox 配置文件。您可以将其参数“general.useragent.override”设置为所需的用户代理字符串。
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference(
"general.useragent.override",
"Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+");
this.driver = new FirefoxDriver(profile);
7. 为浏览器设置 HTTP 代理
与用户代理配置类似,要为 Firefox 设置代理,您只需要设置 Firefox 配置文件的几个参数。
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("network.proxy.type", 1);
firefoxProfile.SetPreference("network.proxy.http", "myproxy.com");
firefoxProfile.SetPreference("network.proxy.http_port", 3239);
driver = new FirefoxDriver(firefoxProfile);
8. 处理 SSL 证书错误
8.1. 处理 FirefoxDriver 的 SSL 证书错误
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.AcceptUntrustedCertificates = true;
firefoxProfile.AssumeUntrustedCertificateIssuer = false;
driver = new FirefoxDriver(firefoxProfile);
8.2. 处理 ChromeDriver 的 SSL 证书错误
您可以使用特殊的 SetEnvironmentVariable 方法在 Windows 中创建一个环境变量,指向您的驱动程序可执行文件的路径。这样,您就不需要在每次初始化驱动程序实例时都指定其路径。
DesiredCapabilities capability = DesiredCapabilities.Chrome(); Environment.SetEnvironmentVariable("webdriver.ie.driver", "C:\\Path\\To\\ChromeDriver.exe"); capability.SetCapability(CapabilityType.AcceptSslCertificates, true); driver = new RemoteWebDriver(capability);
8.3. 处理 ChromeDriver 的 SSL 证书错误
DesiredCapabilities capability = DesiredCapabilities.InternetExplorer();
Environment.SetEnvironmentVariable("webdriver.ie.driver", "C:\\Path\\To\\IEDriver.exe");
capability.SetCapability(CapabilityType.AcceptSslCertificates, true);
driver = new RemoteWebDriver(capability);
9. 将焦点滚动到控件
WebDriver 中没有内置机制可以将焦点滚动到控件。但是,您可以使用 JavaScript 的 window.scroll 方法。您只需要传递所需元素的 Y 坐标。
[TestMethod]
public void ScrollFocusToControl()
{
this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com/compelling-sunday-14022016/");
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));
string jsToBeExecuted = string.Format("window.scroll(0, {0});", link.Location.Y);
((IJavaScriptExecutor)driver).ExecuteScript(jsToBeExecuted);
link.Click();
Assert.AreEqual<string>("10 Advanced WebDriver Tips and Tricks - Part 1", driver.Title);
}
10. 将焦点设置到控件
有两种方法可以完成此任务。第一种方法是使用 IWebElement 的 SendKeys 方法并传递空字符串。第二种方法是使用一点 JavaScript 代码。
[TestMethod]
public void FocusOnControl()
{
this.driver.Navigate().GoToUrl(
@"http://automatetheplanet.com/compelling-sunday-14022016/");
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));
// 9.1. Option 1.
link.SendKeys(string.Empty);
// 9.1. Option 2.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].focus();", link);
}
到目前为止,'使用 WebDriver 进行务实的自动化' 系列