Search code examples
c#classseleniumwebdriverextending

C# Extending Selenium Webdriver Class


I would like to add a static string property that will track the name of the current test running. I figured the best way to go about this was to use the WebDriver since it is the only object that is carried throughout all of my page objects.

Is there a way to extend the WebDriver class to add a string property that I can set?

EDIT: Since WebDriver uses the IWebDriver interface rather would I extend the interface perhaps?

EDIT #2: Adding example of what I currently have to load my WebDriver:

protected static NLog.Logger _logger = LogManager.GetCurrentClassLogger();
protected static IWebDriver _driver;

/// <summary>
/// Spins up an instance of FireFox webdriver which controls the browser using a
/// FireFox plugin using a stripped down FireFox Profile.
/// </summary>
protected static void LoadDriver()
{
    ChromeOptions options = new ChromeOptions();
    try
    {
        var profile = new FirefoxProfile();
        profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream doc xls pdf txt");

        _driver = new FirefoxDriver(profile);
        _driver.Navigate().GoToUrl("http://portal.test-web01.lbmx.com/login?redirect=%2f");
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }
}

Solution

  • You will need to wrap the WebDriver using the "Decorator" design pattern.

    public class MyWebDriver : IWebDriver
    {
        private IWebDriver webDriver;
        public string CurrentTest { get; set; }
    
        public MyWebDriver(IWebDriver webDriver)
        {
            this.webDriver = webDriver
        }
    
        public Method1()
        {
            webDriver.Method1();
        }
    
        public Method2()
        {
            webDriver.Method2();
        }
    
        ...
    }
    

    And then pass in whichever driver you are using at the time.

    var profile = new FirefoxProfile();
    MyWebDriver driver = new MyWebDriver(new FirefoxDriver(profile));
    

    This way you are delegating the interface methods of IWebDriver to FirefoxDriver but can add whatever additions are appropriate.