Webdriver Code Samples

The test binaries that you can upload to Nugridium have to be written using NUnit test fixtures. You can quickly get started by using the code sample provided in this section.

Dynamically reading the url and browser in your NUnit test

Your Webdriver test method should not have a hard coded url and browser. Instead you should be reading those dynamically so that the same test can be executed against multiple urls and browsers. Nugridium requires that you read these values from an xml file that will be created for you at run time. The url and browser type should then be used in your test to instantiate your IWebDriver. The file's name is: "webDriverSettings.xml".

Below is the xml of this file:


    <webDriverSettings>
      <browser>
        <type>Firefox</type>
      </browser>
      <url>
        <base>http://www.your-url.com</base>
      </url>
      <data>Your custom data here</data>
      <testFullName>SeleniumIdeTest.Search_textbox_is_present</testFullName>
      <testId>95</testId>
      <testRunId>85</testRunId>
    </webDriverSettings>

In addition to the browser and url to test, there are xml nodes for 'data' which will hold any custom data you enter, as well as the currently executing test run id and test name.

Below is a small utility class you can use in order to read from that file:


    public class WebDriverSettingsReader
    {
        public static string GetBrowserType()
        {
            var file = getSettingsFilePath();
            var xel = XElement.Load(file);
            return xel.Element("browser").Element("type").Value;
        }
        public static string GetBaseUrl()
        {
            var file = getSettingsFilePath();
            var xel = XElement.Load(file);
            var url = xel.Element("url").Element("base").Value;
            return url;
        }
        private static string getSettingsFilePath()
        {
            // the settings file is at the same level as the executing assembly
            var settingsFileDir = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            var settingsFilePath = Path.Combine(settingsFileDir, "webDriverSettings.xml");
            return settingsFilePath;
        }
    }

Below is factory class you can use to instantiate your Selenium driver using the utility class we saw earlier:


    public class WebDriverFactory
    {
        public static IWebDriver Create()
        {
            var browserType = WebDriverSettingsReader.GetBrowserType();
            IWebDriver driver;
            Logger.Log("Creating web driver for " + browserType);
            switch (browserType)
            {
                case "Firefox":
                    DesiredCapabilities capabilites = DesiredCapabilities.Firefox();
                    driver = new FirefoxDriver(capabilites);
                    break;
                case "Chrome":
                    var options = new ChromeOptions();
                    options.AddArgument("start-maximized");
                    driver = new ChromeDriver(options);
                    break;
                case "IE":
                    var ieOptions = new InternetExplorerOptions
                    {
                        ForceCreateProcessApi = true,
                        BrowserCommandLineArguments = "-private"
                    };
                    driver = (IWebDriver)new InternetExplorerDriver(ieOptions);
                    break;
                default:
                    throw new InvalidOperationException("Unable to find driver for '" + browserType);
            }
            return driver;
        }
    }

Below is an example of how you should use it in your NUnit test fixture:


    [TestFixture]
    public class SeleniumIdeTest
    {
        private IWebDriver driver;
        private string baseURL;
        
        [SetUp]
        public void SetupTest()
        {
            driver = WebDriverFactory.Create();
            baseURL = WebDriverSettingsReader.GetBaseUrl();
        }
        
        [TearDown]
        public void TeardownTest()
        {
            try
            {
                driver.Close();
                driver.Quit();
            }
            catch (Exception ex)
            {
                Logger.Log("Error closing " + WebDriverSettingsReader.GetBrowserType() + " driver, ex: " + ex.Message);
            }
        }
    
        [Test]
        public void Assert_Page_Navigation_Present()
        {
            Logger.Log("Navigating to page " + baseURL);
            driver.Navigate().GoToUrl(baseURL);
            ...
            // take a snapshot
            WebDriverScreenShotTaker.TakeScreenshot(driver);
        }
    }

Webdriver Helper Classes

The following are a few useful code examples that will help you take snapshots, log to the console, an extension method for waiting for an element on a page, etc.

Utility class for taking a snapshot

If you take a snapshot to the current directory in your test method, the Nugridium agent will pick that image up so you can view it in the test detail page on the web portal.

            
    public class WebDriverScreenShotTaker
    {
        public static void TakeScreenshot(IWebDriver driver)
        {
            var screehShot = ((ITakesScreenshot) driver).GetScreenshot();
            var fileName = DateTime.Now.Ticks + ".png";
            var fullPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var dir = Path.GetDirectoryName(fullPath);
            var path = Path.Combine(dir, fileName);

            //screehShot.SaveAsFile(fileName, ImageFormat.Png);

            using(BinaryWriter bw = new BinaryWriter(new FileStream(path, FileMode.Append, FileAccess.Write))){
                bw.Write(imageBytes);
                bw.Close();
            }
        }
    }

        

Utility class for logging to the console

If you log something to the console in your test method that will appear on the test session log for that test method execution.


    public class Logger
    {
        public static void Log(string msg)
        {
            Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd HH':'mm':'ss] - ") + msg);
        }
    }

        

Extension method for the FindElement with an optional 'timeout' parameter

The below extension method adds an optional timeout parameter to the FindElement method that will help you avoid getting missing element errors. You can use it when trying to find an element right after navigating to a url.


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