Running Selenium tests in multiple browsers with a base class

Say I have a code:

namespace SeleniumTests 
{
    [TestFixture(typeof(FirefoxDriver))]
    [TestFixture(typeof(InternetExplorerDriver))]
    public class TestWithMultipleBrowsers<TWebDriver> where TWebDriver : IWebDriver, new()
    {
        private IWebDriver driver;

        [SetUp]
        public void CreateDriver () {
            this.driver = new TWebDriver();
        }

        [Test]
        public void GoogleTest() {
            driver.Navigate().GoToUrl("http://www.google.com/");
            IWebElement query = driver.FindElement(By.Name("q"));
            query.SendKeys("Bread" + Keys.Enter);

            Thread.Sleep(2000);

            Assert.AreEqual("bread - Google Search", driver.Title);
            driver.Quit();
        }
    }
}

I need a block

    [SetUp]
    public void CreateDriver () {
        this.driver = new TWebDriver();
    }

go to the base class. But in this case, I do not know how to inherit from the base class. How to process <TWebDriver> where TWebDriver: IWebDriver, new ()?

+4
source share
1 answer

This does not use generics, as your example, but instead works like dependency injection.

You need a method to create an instance of the web server.

public class DriverFactory
{
    public IWebDriver Driver { get; set; }

    public enum DriverType
    {
        IE,
        Firefox,
        Chrome
    }

    public IWebDriver GetDriver(DriverType typeOfDriver)
    {
        if (typeOfDriver == DriverType.IE) return new InternetExplorerDriver();
        if (typeOfDriver == DriverType.Chrome) return new ChromeDriver();
        return new FirefoxDriver(); // return firefox by default
    }
}

Then call from your installation:

[Setup]
public void CreateDriver()
{
    var driverFactory = new DriverFactory();
    this.driver = driverFactory.GetDriver(DriverType.Chrome);
}

You can inherit a class:

public class TestWithMultipleBrowsers : DriverFactory
+5
source

All Articles