我怎样才能使用类属性使用扩展方法

时间:2015-12-03 14:46:58

标签: c# selenium selenium-webdriver

我有一个硒类

 public class Driver
    {
        public IWebDriver Instance { get; set; }
        public  string baseURL;

        public void Initialize()
        {
            Instance = new FirefoxDriver();
            baseURL = "http://localhost:49730/";
            Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
        }

        public void Wait(TimeSpan timespan)
        {
            Thread.Sleep((int)(timespan.TotalSeconds * 1000));
        }

        public void Close()
        {
            Instance.Close();;
        }
    }

我还创建了一个显式等待的扩展方法

public static class WebDriverExtensionMethods

    public static class WebDriverExtensionMethods
    {
        public static IWebElement WaitAndFindElement(this Driver driver, By by, int timeoutInSeconds)
        {
            if (timeoutInSeconds > 0)
            {
                var wait = new WebDriverWait(driver.Instance, TimeSpan.FromSeconds(timeoutInSeconds));
                return wait.Until(drv => drv.FindElement(by));
            }
            return driver.Instance.FindElement(by);
        }
    }

如何使用Driver类属性调用该方法?即我想调用driver.Instance.WaitAndFindElement

1 个答案:

答案 0 :(得分:2)

也许你可以在IWebDriver上编写扩展名,而不是Driver:

public static class WebDriverExtensionMethods
{
    private static IWebElement WaitAndFindElementInternal(IWebDriver webDriver, By by, int timeoutInSeconds)
    {
        if (timeoutInSeconds > 0)
        {
            var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }
        return webDriver.FindElement(by);
    }

    public static IWebElement WaitAndFindElement(this Driver driver, By by, int timeoutInSeconds)
    {
        return WaitAndFindElementInternal(driver.Instance, by, timeoutInSeconds);
    }

    public static IWebElement WaitAndFindElement(this IWebDriver driver, By by, int timeoutInSeconds)
    {
        return WaitAndFindElementInternal(driver, by, timeoutInSeconds);
    }
}

顺便说一句,这样你只能在驱动程序的Instance属性上调用它。否则,您可以添加此扩展程序以及您已有的扩展程序。甚至可能提取常用代码:

driver.Instance.WaitAndFindElement

这样您就可以拨打driver.WaitAndFindElement以及tapply