Selenium Parallel testing with extension methods Selenium Parallel testing with extension methods selenium selenium

Selenium Parallel testing with extension methods


Ok so there are a few things you need to change. Extension methods have a few rules which we need to follow. The rules are:

  1. It must be in a non generic static class. So the method must be static since you cannot have instance methods in a static class.
  2. It must have one parameter and the first parameter must have this keyword. The first parameter cannot have out or ref.
  3. The first parameter cannot be a pointer type.

So keeping those rules in mind, let's go ahead and create the extension method you need.

namespace ParallelTests{    public static class ExtensionMethods // I would call it ChromeDriverEntension    {        public static void AssertDisplayed(this IWebDriver driver)        {            Assert.IsTrue(driver.FindElement(By.XPath("//*[contains(text(),'Some Text')]")).Displayed);        }    }} 

The above is a nongeneric static class. It has one parameter and the first parameter has this keyword. The first parameter is IWebDriver since this is what we are extending. The method is also static.

Ok let's go ahead and use it.

namespace ParallelTests{    public class Base    {        public IWebDriver Driver { get; set; }    }    public class Hooks : Base    {        public Hooks()        {            Driver = new ChromeDriver();        }    }    [TestFixture]    [Parallelizable]    public class ChromeTesting : Hooks    {        [Test]        public void ChromegGoogleTest()        {            Driver.Navigate().GoToUrl("https://www.google.co.uk");            Driver.FindElement(By.Id("lst-ib")).SendKeys("Deep Purple");            Driver.FindElement(By.Id("lst-ib")).SendKeys(Keys.Enter);            Driver.AssertDisplayed();        }    }}

How the compiler finds the extension method?

When the compiler notices code which looks like instance method, Driver.AssertDisplayed();, but there is no instance method that satisfies the signature, then it looks for an extension method. It searches all the namespaces to find a match. Since this method is in the same namespace above, it will find it. If it was in a different namespace, you would need to import that namespace with using A.B where A.B is the name of the namespace where the extension method is. Otherwise, the compiler will generate an error saying it cannot find such a method.

C# in Depth by Jon Skeet covers extension methods in depth if you want to read more.