4

Let's say I Have 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 want block

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

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

1
  • Good question, but I look at the [SetUp] as a Unit Test Constructor almost. What I do is very similar but instead of creating the new Instance in the [SetUp] I call off to a static method that takes in a Generic IWebDriver and does lots of setup like connects to the Selenium GRID server, sets window size etc. Commented Mar 16, 2015 at 15:52

1 Answer 1

5

This doesn't use generics like your example but instead kind of works like dependency injection.

You need a method to create the instance of the webdriver.

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 setup:

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

You can inherit the class:

public class TestWithMultipleBrowsers : DriverFactory 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. But is this solution allows you to run a single test immediately turn on multiple browsers? Indeed, this is precisely what allows you to do [TestFixture (typeof (ChromeDriver))] [TestFixture (typeof (InternetExplorerDriver))] [TestFixture (typeof (FirefoxDriver))] But I do not understand how to initialize push in the base class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.