Cross Browser Testing in Selenium Examples [2021 Update]

In this post let’s learn Cross Browser Testing in Selenium with examples together. In the web world, users use different browsers such as Chrome, Firefox, Internet Explorer, Opera, and Safari, and so on. These browsers have different behaviors and features. Thus, we should verify web application functionalities are working as expected for all browsers and this testing activity is called cross browser testing. Selenium webdriver supports HtmlUnit Driver, Firefox Driver, Chrome Driver, Opera Driver, MS Edge Driver, MS Internet Explorer Driver, Safari Driver, GhostDriver (PhamtomJS), and so on.

What is Selenium Remote Webdriver?

Selenium webdriver also provides us Remote Webdriver. There are some services such as Sauce Labs or Browser Stack that present us all browsers and their versions in their servers. In order to connect those servers and test web applications with different browsers on the cloud, we use Remote Webdriver. Also, Remote Webdriver is being used for Grid implementations. In another post, I will explain how to use Remote Webdriver and how to test in the cloud.

Due to the nature of the diversity of browsers we face different browser behaviors. In order to cover all browsers while we are automating a website, we should think about different synchronizations, different startup procedures, and so on.

Cross Browser Testing in Selenium with Firefox Driver

Firefox driver is the built-in driver so you do not need to do it for installation. Its startup period is relatively slow.

Declaration: driver = new FirefoxDriver();

Firefox Driver Profile and Options

Profiles and options provide us to declare drivers with extra capabilities and configurations. In the below code, I have used bonigarcia library to set up the Firefox driver.

@Test
public void T01_FirefoxTest() {
    WebDriverManager.firefoxdriver().setup();
    //Create a new Profile
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    //Setting Preferences
    profile.setPreference("intl.accept_languages", "no,en-us,en");
    //Declaring Webdriver instance
    driver = new FirefoxDriver(options.setProfile(profile));
    driver.navigate().to("https://www.swtestacademy.com");
}

Desired Capabilities

DesiredCapabilities provides to set properties for the WebDriver such as BrowserName, Platform, Version, etc. We can configure all driver instance like FirefoxDriver, ChromeDriver, InternetExplorerDriver using desired capabilities. It is very useful when we are using RemoteWebdriver to test on the cloud by using Browserstack or Saucelabs. Also, we can set a manual proxy with DesiredCapabilities. This temporarily changes the system’s proxy settings and when the test finishes, it will change the system to the original state. 

I will show you a proxy test example but before running this proxy test code you should install Burp Suite and set localhost:8080 (127.0.0.1:8080) as a proxy as shown below.

Cross Browser Testing in Selenium

Proxy Example:

@Test
public void T02_DesiredCapabilitiesTest(){
    //Setup Firefox Driver by Bonigarcia Library.
    WebDriverManager.firefoxdriver().setup();

    //Setup Proxy
    String httpProxy = "127.0.0.1:8080";
    Proxy seleniumProxy = new org.openqa.selenium.Proxy();
    seleniumProxy.setHttpProxy(httpProxy)
        .setFtpProxy(httpProxy)
        .setSslProxy(httpProxy);

    //Create Desired Capabilities
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(PROXY, seleniumProxy);
    FirefoxOptions options = new FirefoxOptions(capabilities);

    //Instantiate driver and open the page
    driver = new FirefoxDriver(options);
    driver.navigate().to("http://www.swtestacademy.com");
}

Test Result:
After running the above test code, you will see the GET methods as shown below.

Cross Browser Testing

Cross Browser Testing with HTMLUnit Driver

It is developed by sourgeforge.net (http://htmlunit.sourceforge.net/)

HtmlUnit is a “GUI-Less browser for Java programs”. It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc… just like you do in your “normal” browser.

It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating Chrome, Firefox, or Internet Explorer depending on the configuration used. 

It is faster but I recommend using HTMLUnit Driver for basic automation scenarios.

First, you need to add its dependency to your project.

<dependency>
    <groupId>net.sourceforge.htmlunit</groupId>
    <artifactId>htmlunit</artifactId>
    <version>2.49.1</version>
</dependency>

Then, you can use it as follows:

@Test
@SneakyThrows
public void T03_HtmlUnitDriverTest() {
    //Instantiate driver and open the page
    WebClient webClient = new WebClient();
    //Disable JavaScript processing for one WebClient,
    webClient.getOptions().setJavaScriptEnabled(false);
    webClient.getPage("http://www.swtestacademy.com");
    //Enable JavaScript processing for one WebClient,
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getPage("http://www.google.com");
}

Ghost Driver (PhantomJS)

It is a headless driver, which means when you run it, you won’t see a browser window but you can do everything related to web testing. In order to use GhostDriver, you should add the below maven dependency into your project. (link: phantomjsdriver)

<dependency>
    <groupId>com.codeborne</groupId>
    <artifactId>phantomjsdriver</artifactId>
    <version>1.4.4</version>
</dependency>

And you must download the PhantomJS executable from http://phantomjs.org/download.html and place it under your project directory and declare it in your test automation code.

A sample example is shown below.

Windows Example:

import org.junit.AfterClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
import static org.junit.Assert.assertEquals;

public class GhostDriverTest {
    //Declare PhantomJS path
    public static final File PhantomJS_EXE = new File(System.getProperty("user.dir"), "src/tools/phantomjs-2.1.1-windows/bin/phantomjs.exe");
    static WebDriver driver;

    @Test
    public void GhostDriverTest() {
        //Desired Capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setJavascriptEnabled(true);
        caps.setCapability("phantomjs.binary.path", PhantomJS_EXE.getAbsolutePath());

        //Declare PhantomJS Driver
        driver = new PhantomJSDriver(caps);

        //Go to swtestacademy and check title
        driver.get("http://www.swtestacademy.com");
        assertEquals("Title is not correct!","Software Test Academy", driver.getTitle());
    }

    //Close Driver
    @AfterClass
    public static void quitDriver() {
        driver.quit();
    }
}

Mac Example:

@Test
@SneakyThrows
@Disabled("It has some problems.")
public void T04_PhantomJSTest() {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("phantomjs.binary.path", "/usr/local/bin/phantomjs");
    driver = new PhantomJSDriver(caps);
    driver.navigate().to("https://www.google.com");
}

Note: PhantomJS has threw an error on my mac machine. If you find a solution to pass this problem, please write a comment. Error: java.lang.NoSuchMethodError: ‘void org.openqa.selenium.remote.service.DriverService.<init>(java.io.File, int, com.google.common.collect.ImmutableList, com.google.common.collect.ImmutableMap)’

Cross Browser Testing with Chrome Driver

ChromeDriver is a standalone server that implements WebDriver’s wire protocol for Chromium. ChromeDriver is available for Chrome on Android and Chrome on Desktop (Mac, Linux, Windows, and ChromeOS). [4]

In order to use ChromeDriver, you should specify its location via the webdriver.chrome.driver system property. The sample test code for the chrome driver is shown below. 

Windows Example:

import org.junit.*;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import static org.junit.Assert.assertEquals;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ChromeDriverTest {
    static WebDriver driver;

    //Setup ChromeDriver
    @BeforeClass
    public static void setupTest()   {
        //Declare ChromeDriver Path
        String currentDir = System.getProperty("user.dir");
        System.out.print("current dir: " + currentDir);
        String chromeDriverLocation = currentDir + "\\src\\tools\\chromedriver.exe";
        System.out.print("chrome dir: " + chromeDriverLocation);
        System.setProperty("webdriver.chrome.driver", chromeDriverLocation);
    }

    @Test
    public void T01_basicChromeDriverTest()   {
        //Declare ChromeDriver
        driver = new ChromeDriver();

        //Go to www.swtestacademy.com
        driver.get("http://www.swtestacademy.com");
        assertEquals("Title is not correct!","Software Test Academy", driver.getTitle());
    }

    @Test
    public void T02_optionsChromeDriverTest() {
        //Define Chrome Options
        ChromeOptions options = new ChromeOptions();
        options.addArguments("test-type");
        options.addArguments("disable-plugins");
        options.addArguments("disable-extensions");

        //Declare Chrome driver with options
       driver = new ChromeDriver(options);

        //Go to www.swtestacademy.com
        driver.get("http://www.swtestacademy.com");
        assertEquals("Title is not correct!", "Software Test Academy", driver.getTitle());
    }

    //Close Driver
    @After
    public void quitDriver() {
        driver.quit();
    }
}

On Mac, you can refer to this article: https://www.swtestacademy.com/install-chrome-driver-on-mac/

And below I want to share an example with Bonigarcia Webdriver Manager:

@Test
public void T05_ChromeTest() {
    WebDriverManager.chromedriver().setup();
    ChromeOptions options = new ChromeOptions();
    options.setHeadless(true);
    driver = new ChromeDriver(options);
    driver.navigate().to("https://www.google.com");
}

IE Driver

First, you have to download IEdriver executable file from here: http://www.seleniumhq.org/download/

Then we should set the “webdriver.ie.driver” to the location of the driver executable and declare IEdriver as follows.

Declaration: Driver = new InternetExplorerDriver();

Important Note!

Problem: When I tried to do the test with IEdriver I got OpenQA.Selenium.NoSuchWindowException : Unable to get browser” problem.

Solution: I solved this problem to set all security zones to the same Protected Mode setting.

Setting the Local Intranet zone’s Enable Protected Mode setting to true solved the problem

  1. Select Tools > Internet Options and go to the Security tab.
  2. Select each zone (Internet, Local intranet, Trusted sites, Restricted sites) and check the Enable Protected Mode check box.

Also, if the above solution doesn’t work, then try to add the test domain to the list of “Trusted Sites”. This may solve this problem. You can do this on the Security tab of Internet Options.

Reference: http://www.michael-whelan.net/selenium-webdriver-and-ie11/

Test Code:

import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import static org.junit.Assert.assertEquals;

public class IEDriverTest {
    static WebDriver driver;

    //Setup IEDriver
    @BeforeClass
    public static void setupTest()   {
        //Declare IEDriver Path
        String currentDir = System.getProperty("user.dir");
        System.out.print("current dir: " + currentDir + "\n");
        String IEDriverLocation = currentDir + "\\src\\tools\\IEDriverServer.exe";
        System.out.print("IE directory: " + IEDriverLocation + "\n");
        System.setProperty("webdriver.ie.driver", IEDriverLocation);
    }

    @Test
    public void basicIEDriverTest() throws InterruptedException {
        //DesiredCapabilities (You can set IE version with below desired capabilities lines.)
        /*DesiredCapabilities capability = new DesiredCapabilities();
        capability.setCapability(CapabilityType.BROWSER_NAME, "internet explorer");
        capability.setCapability(CapabilityType.VERSION, "8");
        capability.setCapability(CapabilityType.PLATFORM, "WINDOWS");*/


        //Declare IEDriverhttp://www.swtestacademy.com/wp-admin/post-new.php#
        //driver = new InternetExplorerDriver(capability);  //Use it when enable DesiredCapabilities
        driver = new InternetExplorerDriver();
        driver.manage().window().maximize();

        //Go to www.swtestacademy.com
        driver.get("http://www.swtestacademy.com");
        assertEquals("Title is not correct!", "Software Test Academy", driver.getTitle());
    }

    //Close Driver
    @After
    public void quitDriver() {
        driver.quit();
    }
}

MS Edge Driver

If you are using Windows 10 and if you need to do test automation with MS Edge browser, you should do this in this way.

First, you have to download MS Edge Driver from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

Then, you should set a driver path, declare an EdgeDriver and use it as follows:

//Set Edge Driver Path
File file = new File("C:\\Program Files (x86)\\Microsoft Web Driver\\MicrosoftWebDriver.exe");
System.setProperty("webdriver.edge.driver", file.getAbsolutePath());

//Declare EdgeDriver
WebDriver driver = new EdgeDriver();

//Use Edge Driver
driver.get("www.www.swtestacademy.com");

There is a nice article about MS Edge Driver here: http://afourtech.com/automation-testing-on-microsoft-edge-browser-using-selenium-web-driver/

With Bonagarcia Webdriver Manager the code as follows:

@Test
public void T06_EdgeTest() {
    WebDriverManager.edgedriver().setup();
    EdgeOptions options = new EdgeOptions();
    options.setHeadless(true);
    driver = new EdgeDriver(options);
    driver.navigate().to("https://www.google.com");
}

Opera Driver

By using Bonigarcia Webdriver manager the code as follows: 

@Test
public void T07_OperaTest() {
    WebDriverManager.operadriver().setup();
    driver = new OperaDriver();
    driver.navigate().to("https://www.google.com");
}

Also, you can download the driver and set the path and create the Opera driver in that way like how we did like Chrome.

Safari Driver

SafariDriver usage is described here: https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari 

I can summarize what you need to do.

First, run below command:

/usr/bin/safaridriver –enable 

Now, we can move the driver a path which is defined as a path in your system. You can check them with the below command and you will see that /usr/local/bin folder is defined as a global path on your system.

sudo nano /etc/paths

Then, you can use the Safari Driver as follows:

@Test
public void T08_SafariTest() {
    driver = new SafariDriver();
    driver.navigate().to("https://www.google.com");
}

Common Problems of Cross Browser Testing in Selenium

While doing cross-browser testing, you may face problems and failures. Different browsers have different driver implementations and these drivers have different behaviors, timing issues, selector differences, implementations bugs, driver implementation scope is not complete (some functionalities are missing), and so on.

When you get this kind of error, I suggest you read the driver log and search for this problem on the internet. Also if you are setting up a new test automation framework, try to implement cross-browser testing as early as possible and see the problems at early phases. You can solve your problems easily in the early phases of your test automation framework.

Github Project

https://github.com/swtestacademy/selenium-examples/tree/main/src/test/java/crossbrowser

References

https://code.google.com/p/selenium/wiki/AdvancedUserInteractions 

https://code.google.com/p/selenium/wiki/DesiredCapabilities 

http://htmlunit.sourceforge.net/ 

https://sites.google.com/a/chromium.org/chromedriver/ 

Thanks,
Onur

2 thoughts on “Cross Browser Testing in Selenium Examples [2021 Update]”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.