Start a personal dev blog on your domain for free with Hashnode and grow your readership.
Get Started

Selenium Firefox Driver: Automate Testing With Firefox Browsers

With 4.25% of browser market share worldwide in June 2020 as per statcounter, Mozilla Firefox browsers are considered inevitable for every Selenium testing checklist. Mozilla developers introduced Geckodriver, also known as the Selenium Firefox Driver to help testers automate browser testing with Firefox browsers.

In this article, we will look into the basics of Selenium Firefox Driver, how to download and set it up in your system. We will then run an automation script using Selenium Firefox Driver to test on Mozilla Firefox browsers.

What Is a Selenium Firefox Driver?

Every browser has a unique engine responsible for rendering the UI of your website. Gecko has been the browser engine responsible for displaying web elements over the Mozilla Firefox browsers.

GeckoDriver also is known as Selenium Firefox Driver serves as a proxy that performs your Selenium tests over a Firefox browser instance. When you perform Selenium testing with Firefox, a JSON wire protocol feeds instructions to the Selenium Firefox Driver i.e. Selenium GeckoDriver. Then GeckoDriver then performs relevant actions in the browser instance based on the instructions and sends the response in HTTP protocol through an HTTP server. Here is an image that explains the architecture of a Selenium WebDriver. You can notice where Selenium Firefox Driver comes into play.

selenium-webdriver-architecture

Should You Include GeckoDriver In Your Selenium Testing Scripts?

Although not the most popular browser, Mozilla Firefox has been a renowned participant in the browser wars ever since its inception in 2002. Firefox still commands a good amount of browser market share after Chrome. I am sure you might have entertained an argument over Google Chrome vs Mozilla Firefox at some point. In fact, many of my colleagues prefer Mozilla Firefox as their default browser instead of Google Chrome. Let us look at the browser market share from June 2019 to July 2020.

Now, 8.48% looks a lot less when compared to 69.42% market share of Google Chrome but did you notice something?

Mozilla Firefox is the third most popular desktop browser and is having a neck to neck race with Safari.

So, Should You Include Firefox Driver In Your Selenium Testing Scripts?

Yes, without a doubt. Having a solid 8.48% browser market share, Firefox browsers has become inevitable for cross browser testing. If you won’t include Firefox Driver in your Selenium testing scripts then you could miss out on a lot of potential leads and promising customers.

With that said, let’s download & set up the Selenium Firefox Driver in your operating system.

Download & Setup GeckoDriver / Firefox Driver For Selenium Project

Step 1: Selenium Firefox Driver or Selenium GeckoDriver can be downloaded from the official GitHub repository of Mozilla. Go to the link and scroll towards the bottom of the page. Open the Assets menu and download the Selenium Firefox Driver respective to your operating system.

Setup GeckoDriver

Step 2: Extract the downloaded file.

Step 3: Copy the GeckoDriver (geckodriver.exe) to the folder where the Firefox browser is located. By doing so, you can avoid giving the absolute path of the Selenium GeckoDriver if the Selenium Firefox Driver instance is created in the test code.

Selenium Firefox Driver

Invoking Selenium Firefox Driver For Selenium Projects

In order to use the Selenium with GeckoDriver or Selenium FirefoxDriver, the corresponding package (or class) has to be included before initializing a new instance of Firefox class. Here are some of the ways in which Selenium with GeckoDriver can be used through popular languages.

Selenium C

...........................
using OpenQA.Selenium.Firefox;
...........................
...........................

namespace Firefox_Demo
{
    class Firefox_Demo
    {
        ...........................
        ...........................
        IWebDriver driver;

        [SetUp]
        public void start_Browser()
        {
            driver = new FirefoxDriver();
            driver.Manage().Window.Maximize();
        }
        ...........................
        ...........................
        [TearDown]
        public void close_Browser()
        {
            driver.Quit();
        }
    }
}

Python

...........................
from selenium import webdriver
...........................
...........................

class Automation_Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.maximize_window()
        ...........................
        ...........................
    def tearDown(self):
        Quit selenium driver
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

Java

package org.package_name;
import org.openqa.selenium.firefox.FirefoxDriver;
...........................
...........................

public class ClassTest{
    private WebDriver driver;
    ...........................
    ...........................

    @BeforeClass
    public void setUp(){
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        ...........................
        ...........................
    }

    ...........................
    ...........................

    @AfterClass
    public void tearDown() throws Exception {
       if (driver != null) {
           driver.quit();
        }
    }
}

For further demonstration, we will be using the Selenium for GeckoDriver with NUnit framework for running Selenium C# testing. If you are new to Selenium C#, you can refer to our Selenium C# tutorial.

Selenium C# Testing with Firefox Driver Using NUnit Framework

NUnit is a popular open-source web-testing framework. It is used with Selenium C# for automated browser testing. The extensive feature-set of the NUnit framework makes it a more popular framework when compared to other frameworks like MSTest/Visual Studio, xUnit.NET, etc. These frameworks can also be used with C# and Selenium test suite.

Assertions in NUnit are instrumental in making the code more modular so that less effort is spent on the maintenance of the source code.

We won’t delve into the internals of the NUnit framework since we have already an article covering the NUnit framework with Selenium along with steps for installation on Visual Studio. You should check out the NUnit tutorial for getting started with the NUnit framework.

Here is the basic execution flow of an NUnit test. The necessary steps for Initialization and De-initialization are performed as a part of the [Setup] and [TearDown] annotation.

NUnit test

With the basic flow in mind. Let’s get our hands dirty with test automation using Selenium and Geckodriver with NUnit. To demonstrate Selenium test automation with NUnit, we have two sample test cases; details of which are mentioned below-

Test Case – 1

  1. Navigate to the URL https://lambdatest.github.io/sample-todo-app/
  2. Select the first two checkboxes
  3. Send ‘Adding item to the list’ to the textbox with id = sampletodotext
  4. Click the Add Button and verify whether the text has been added or not

Test Case – 2

  1. Navigate to the URL https://www.lambdatest.com
  2. Locate the hover element with description as ‘Automated’
  3. Click on the Learn More option to open the target web page
  4. Raise assert if the driver title does not match the expected title

Implementation for testing with Selenium Firefox Driver & NUnit

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;

namespace Firefox_Demo
{
    class Firefox_Demo
    {
        String test_url_1 = "https://lambdatest.github.io/sample-todo-app/";
        String test_url_2 = "https://www.lambdatest.com";
        IWebDriver driver;

        [SetUp]
        public void start_Browser()
        {
            driver = new FirefoxDriver();
            driver.Manage().Window.Maximize();

        }

        [Test, Order(1)]
        public void test_ff_1()
        {
            driver.Url = test_url_1;
            String itemName = "Adding item to the list";

            System.Threading.Thread.Sleep(2000);

            // Click on First Check box
            IWebElement firstCheckBox = driver.FindElement(By.Name("li1"));
            firstCheckBox.Click();

            // Click on Second Check box
            IWebElement secondCheckBox = driver.FindElement(By.Name("li2"));
            secondCheckBox.Click();

            // Enter Item name
            IWebElement textfield = driver.FindElement(By.Id("sampletodotext"));
            textfield.SendKeys(itemName);

            // Click on Add button
            IWebElement addButton = driver.FindElement(By.Id("addbutton"));
            addButton.Click();

            // Verified Added Item name
            IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span"));
            String getText = itemtext.Text;

            // Check if the newly added item is present or not using
            // Condition constraint (Boolean)
            Assert.That((itemName.Contains(getText)), Is.True);

            /* Perform wait to check the output */
            System.Threading.Thread.Sleep(2000);

            Console.WriteLine("Firefox - Test 1 Passed");
        }

        [Test, Order(2)]
        public void test_ff_2()
        {
            driver.Url = test_url_2;
            String hover_xpath = "/html/body/div[2]/section[2]/div/div/div[2]/div/div[1]";
            String learn_more_xpath = "/html/body/div[2]/section[2]/div/div/div[2]/div/div[1]/div[2]/span/a";
            String expected_url_title = "Online Appium and Selenium Automation Testing Tool | Selenium Grid for Web Automation Testing";

            System.Threading.Thread.Sleep(2000);

            IJavaScriptExecutor js = driver as IJavaScriptExecutor;

            js.ExecuteScript("window.scrollBy(0,500)");

            var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
            var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath(hover_xpath)));

            Actions action = new Actions(driver);
            action.MoveToElement(element).Perform();

            // Since the element is visible, we should perform a click on the Know More section

            var more_element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath(learn_more_xpath)));
            more_element.Click();

            /* Perform wait to check the output */
            System.Threading.Thread.Sleep(2000);

            String url_title = driver.Title;

            Assert.That(expected_url_title, Is.EqualTo(url_title));

            Console.WriteLine("Firefox - Test 2 Passed");
        }

        [TearDown]
        public void close_Browser()
        {
            driver.Quit();
        }
    }
}

Code Walkthrough (Common Step)

Since Firefox browser is used for cross browser testing, we created a Firefox Web Driver instance before any of the tests are executed. IWebDriver (which is a part of OpenQA.Selenium namespace) is used to create the Selenium Firefox Driver instance.

namespace Firefox_Demo
{
    class Firefox_Demo
    {
        ......................................
        ......................................
        IWebDriver driver;

        [SetUp]
        public void start_Browser()
        {
            driver = new FirefoxDriver();
            driver.Manage().Window.Maximize();
        }
    }
    ......................................
    ......................................
}

This initialization is done as a part of the implementation in the [SetUp] annotation. The de-initialization process i.e. freeing Selenium Firefox Driver instance is done as a part of the implementation in the [TearDown] annotation.

Test Case – 1

Using the Inspect tool of the Firefox browser, we find elements (check-boxes) with name li1, li2

tool of the Firefox browser

Once the check-boxes are located, we locate the text-box where the target text has to be added. We make use of XPath to do the same. Assert with Boolean condition constraint is used to verify the correctness of the test case.

IWebElement textfield = driver.FindElement(By.Id("sampletodotext"));
textfield.SendKeys(itemName);
// Click on Add button
IWebElement addButton = driver.FindElement(By.Id("addbutton"));
addButton.Click();

Shown below is the execution snapshot where we can see that the new item has been added to the list-

firefoxdriver

Test Case – 2

To locate the element with display name Automation, we make use of the ExecuteScript method to execute JavaScript in the context of the current window.

Automation-testing

We perform a vertical scroll by 500 pixels since the element being searched can only be located after the scroll.

IJavaScriptExecutor js = driver as IJavaScriptExecutor;

js.ExecuteScript("window.scrollBy(0,500)");

Wait of 30 seconds is added to ensure that the element is visible. Once the element (name = Automation) is visible, a Hover operation is performed using the MoveToElement() method of the Actions class.

var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath(“/html/body/div[2]/section[2]/div/div/div[2]/div/div[1]”)));

Actions action = new Actions(driver);
action.MoveToElement(element).Perform();

A click on the ‘Learn More’ link for the Automation option (shown in the earlier snapshot) is performed. Once the new page opens, a comparison of the expected window title with the title of the current page is performed using EqualTo constraint. Assert is raised if the titles do not match.

selenium-automation-testing

String url_title = driver.Title;

Assert.That(expected_url_title, Is.EqualTo(url_title));

Kudos! You have executed the test cases using the Selenium Firefox Driver & NUnit framework on your machine.

“How do you plan to test these scripts over multiple Firefox browser versions?”

You can’t keep installing and uninstalling one browser version after the other in your machine and having different browser versions configured over multiple machines is going to leave you in a spot where you are more likely to spend more time in maintaining different Firefox browser versions rather than testing on them.

A better option for improving the test coverage is to perform Selenium automation testing on a cloud-based cross browser testing like LambdaTest. Using LambdaTest, you can perform automated and live interactive cross browser testing on 2000+ real browsers and operating systems. With LambdaTest, you can test over legacy & latest browser versions of Mozilla Firefox, Google Chrome, Safari, Opera, Edge, and more. Plus you can leverage our online Selenium Grid to help you execute multiple instances of Selenium Firefox Driver in parallel.

Remote Testing with NUnit & Selenium Firefox Driver Over LambdaTest

To get started, you need to create an account on LambdaTest. Once the account is created, you should make a note of the user-name & access-key required for accessing the remote Selenium Grid on LambdaTest. This information is available in your Profile section of LambdaTest.

Selenium Grid

You can generate browser and platform capabilities on which testing is to be performed using LambdaTest capabilities generator. Shown below are the desired capabilities for Firefox 62.0 on the Windows 10 operating system:

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability("user","Your Lambda Username")
capabilities.SetCapability("accessKey","Your Lambda Access Key")
capabilities.SetCapability("build", "your build name");
capabilities.SetCapability("name", "your test name");
capabilities.SetCapability("platform", "Windows 10");
capabilities.SetCapability("browserName", "Firefox");
capabilities.SetCapability("version","62.0");

LambdaTest capabilities generator

For demonstration of Selenium test automation (using NUnit framework) on the remote Selenium GeckoDriver/ Firefox Driver, we port the previous example implementation to make it work with LambdaTest infrastructure.

Below are the overall requirements for automated cross browser testing:

  • Browser – Firefox
  • Browser version – 62.0
  • Operating System – Windows 10
  • Resolution – 1024 * 768

Implementation

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
/* For using Remote Selenium WebDriver */
using OpenQA.Selenium.Remote;

namespace Firefox_Demo
{
    class Firefox_Demo
    {
        String test_url_1 = "https://lambdatest.github.io/sample-todo-app/";
        String test_url_2 = "https://www.lambdatest.com";
        IWebDriver driver;

        [SetUp]
        public void start_Browser()
        {
            // Profile details at https://accounts.lambdatest.com/profile
            String username = "user-name";
            String accesskey = "access-key";
            String gridURL = "@hub.lambdatest.com/wd/hub";

            // Local Selenium WebDriver
            //driver = new FirefoxDriver();

            //Start - Implementation of Remote Selenium WebDriver
            DesiredCapabilities capabilities = new DesiredCapabilities();

            capabilities.SetCapability("user", username);
            capabilities.SetCapability("accessKey", accesskey);
            capabilities.SetCapability("build", "Using Firefox WebDriver using C# and NUnit");
            capabilities.SetCapability("name", "Using Firefox WebDriver using C# and NUnit");
            capabilities.SetCapability("platform", "Windows 10");
            capabilities.SetCapability("browserName", "Firefox");
            capabilities.SetCapability("version", "62.0");

            driver = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), capabilities, TimeSpan.FromSeconds(600));
            //End - Implementation of Remote Selenium WebDriver

            driver.Manage().Window.Maximize();

        }

        [Test, Order(1)]
        public void test_ff_1()
        {
            driver.Url = test_url_1;
            String itemName = "Adding item to the list";

            System.Threading.Thread.Sleep(2000);

            // Click on First Check box
            IWebElement firstCheckBox = driver.FindElement(By.Name("li1"));
            firstCheckBox.Click();

            // Click on Second Check box
            IWebElement secondCheckBox = driver.FindElement(By.Name("li2"));
            secondCheckBox.Click();

            // Enter Item name
            IWebElement textfield = driver.FindElement(By.Id("sampletodotext"));
            textfield.SendKeys(itemName);

            // Click on Add button
            IWebElement addButton = driver.FindElement(By.Id("addbutton"));
            addButton.Click();

            // Verified Added Item name
            IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span"));
            String getText = itemtext.Text;

            // Check if the newly added item is present or not using
            // Condition constraint (Boolean)
            Assert.That((itemName.Contains(getText)), Is.True);

            /* Perform wait to check the output */
            System.Threading.Thread.Sleep(2000);

            Console.WriteLine("Firefox - Test 1 Passed");
        }

        [Test, Order(2)]
        public void test_ff_2()
        {
            driver.Url = test_url_2;
            String hover_xpath = "/html/body/div[2]/section[2]/div/div/div[2]/div/div[1]";
            String learn_more_xpath = "/html/body/div[2]/section[2]/div/div/div[2]/div/div[1]/div[2]/span/a";
            String expected_url_title = "Online Appium and Selenium Automation Testing Tool | Selenium Grid for Web Automation Testing";

            System.Threading.Thread.Sleep(2000);

            // Verified Added Item name
            //IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span"));

            IJavaScriptExecutor js = driver as IJavaScriptExecutor;

            js.ExecuteScript("window.scrollBy(0,500)");

            var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
            var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath(hover_xpath)));

            Actions action = new Actions(driver);
            action.MoveToElement(element).Perform();

            // Since the element is visible, we should perform a click on the Know More section

            var more_element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath(learn_more_xpath)));
            more_element.Click();

            /* Perform wait to check the output */
            System.Threading.Thread.Sleep(2000);

            String url_title = driver.Title;

            Assert.That(expected_url_title, Is.EqualTo(url_title));

            Console.WriteLine("Firefox - Test 2 Passed");
        }

        [TearDown]
        public void close_Browser()
        {
            driver.Quit();
        }
    }
}

Code Walkthrough

In the current test case, we import the OpenQA.Selenium.Remote package/namespace where RemoteWebDriver class is defined.

/* For using Remote Selenium WebDriver */
using OpenQA.Selenium.Remote;

Username and access key combination is passed to the remote Selenium Grid on which Selenium automation testing is performed.

String username = "user-name";
String accesskey = "access-key";
String gridURL = "@hub.lambdatest.com/wd/hub";
.......................................................................
.......................................................................

The browser & platform capabilities that are generated using the LambdaTest capabilities generator passed as an argument to the Remote Selenium Firefox Driver interface.

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.SetCapability("user", username);
capabilities.SetCapability("accessKey", accesskey);
capabilities.SetCapability("build", "Using Firefox WebDriver using C# and NUnit");
capabilities.SetCapability("name", "Using Firefox WebDriver using C# and NUnit");
capabilities.SetCapability("platform", "Windows 10");
capabilities.SetCapability("browserName", "Firefox");
capabilities.SetCapability("version", "62.0");

.................................................................................
.................................................................................
.................................................................................

driver = new RemoteWebDriver(new Uri("https://user-name:access-key@hub.lambdatest.com/wd/hub"), capabilities, TimeSpan.FromSeconds(600));

The rest of the implementation which contains the business logic of the test cases remains unchanged. The effort spent to port the existing code implementation from your Local Selenium Firefox Driver to LambdaTest’s Remote Selenium Firefox Driver is minimal.

After you execute the test scripts using Selenium, Geckodriver & LambdaTest, you can visit Automation Logs to check the status of the test.

Selenium Firefox Driver

As seen in the above snapshot, the test status is Completed i.e. test has passed. You can even find the execution video that was recorded in real-time when the Selenium automation testing was performed.

awesome

Conclusion

Mozilla Firefox holds a dominant position in the browser wars. So developers need to keep cross browser development practices in mind. And testers need to incorporate Selenium Geckodriver or Selenium Firefox Driver in their Selenium testing suites.

Maintaining an in-house Selenium Grid infrastructure can come back to haunt you later down the road. It would be best to port your existing Selenium test suites to an online Selenium Grid. Your existing Selenium testing setup can be easily ported to LambdaTest’s cloud Selenium Grid. with minimal changes in the implementation. This enables developers to test their code against not just Firefox versions but many more major browser vendors such as Google Chrome, Safari, Edge, Opera, Yandex, and even the notorious IE. Use LambdaTest Selenium rid now for free and improve the overall test coverage – an important KPI for every business running online. Happy Testing ☺

Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

No Comments Yet