我正在使用 .NET 4.5
、VS2013
和 Selenium
。
我正在为页面流结构和字段结构有些相似的产品编写 selenium 测试。
要为我在 IWebDriver
上使用扩展方法的字段设置值
例子:
private void WillsCustomerDetail(IWebDriver driver)
{
driver.WillsSetMainCustomerTitle("Dr");
driver.WillsSetMainCustomerGender("Male");
driver.WillsSetMainCustomerName("Liufa");
driver.WillsSetMainCustomerSurname("Afuil");
driver.WillsSetMainCustomerDateOfBirth(new DateTime(1955, 12, 26));
...
}
public static IWebElement WillsSetMainCustomerName(this IWebDriver driver, string value)
{
return driver.SetText(value, WillsElements.CustomerDetails.MainCustomer.Firstname);
}
public static IWebElement SetText(this IWebDriver driver, string value, string selector)
{
var element = driver.FindElement(By.CssSelector(selector));
element.SendKeys(value);
return element;
}
public static class WillsElements
{
public static class CustomerDetails
{
public static class MainCustomer
{
public static string Title
{
get { return "#Customers-0--Title"; }
}
...
}
}
}
我遇到的问题是我的方法命名
WillsSetMainCustomerTitle
- 实际上是
的串联
遗嘱 - 产品(网络旅程),
MainCustomer - 部分页面,
标题 - 字段,
对于下一个产品,我将有 LpaSetMainCustomerName
和大多数其他字段,这使它变得一团糟。
我想要的是
driver.Wills.MainCustomer.SetTitle("Dr");
作为扩展方法
有没有办法实现分组扩展方法? (或者得到类似的东西,在仍然有扩展方法的同时允许很好的分组)。
最佳答案
不可能直接对这样的扩展方法进行分组。
在例子中
driver.Wills.MainCustomer.SetTitle("Dr");
您可以制作 Wills
和 MainCustomer
方法,每个方法都返回一个专门的类型。下一个级别(MainCustomer
和 SetTitle
)的钻取可以关闭这些类型。搜索“流利的风格”看看我的意思。我不推荐这里。它创建了大量的工作来设置只是为了在您想要的地方获得那个小句点字符。
你也可以包装驱动程序:
new WillsDriver(driver)
.MainCustomer
.Title = "Dr";
同样,您必须编写所有这些类和成员。
我可以建议以下命名约定:
Wills_MainCustomer_SetTitle
一个非常简单的解决方案,使它更具可读性。
如果这些方法的主体总是非常相似,请考虑使用 T4 模板来生成这些方法的所有可能情况。
关于c# - 分组扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28063883/