Stimulate Network Throttling in Selenium (Java)

Overview

When automating test case using Selenium, there are some special cases which you need to emulate network throttling. Fortunately, Selenium provides a way to simulate different network conditions through Chrome DevTools protocol.

In this article, let’s find out how we can emulate network throttling for Chrominum browser (Chrome/MS Edge…) in Selenium (Java).

Note that, I will not focus on how to set up a basic Selenium (Java) project from beginning. If you do not know how, please refer to Selenium docs or do some Google search first.

Also note that, you should consider upgrade your project to Selenium 4.xx because any version under its might not work as expected. The newest Selenium version using in this article is 4.8.3 (latest until 2023/04/09)

Getting Started

To get started, you need to create a MAVEN project using your favorite IDE (recommend Intelij IDE). And modify your pom.xml like below. Do not forget to refresh your project to update changes.

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.8.3</version>
    </dependency>
 
    <dependency>
        <groupId>io.github.bonigarcia</groupId>
        <artifactId>webdrivermanager</artifactId>
        <version>5.3.2</version>
    </dependency>
<dependencies>

Create a StimulateNetworkThrottle.java file in src/test/java folder. Finish this and now you are good to go!

Emulate Network Throttling in Chrome

Below is a simple Selenium code which redirects to a website:

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class StimulateNetworkThrottle {

    public static void main(String[] args) throws InterruptedException {

        // create Chrome driver instance
        WebDriver driver = WebDriverManager.chromedriver().create();

        // get current time in specific format and print out start time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("Start = " + LocalDateTime.now().format(formatter));

        // redirect to specific URL
        driver.get("https://ericsson.com");
        driver.manage().window().maximize();

        // print out end time to calculate total amount of time extends because of network throttling
        System.out.println("End = " + LocalDateTime.now().format(formatter));


        //close browser and quit driver
        driver.quit();
    }
}

Run above code and you can watch the logged time:

Seconds to run in normal network

=> As you can see in normal network condition, it only takes 1-2 seconds to finish running.

Now to emulate network throttling, you just need to break down these steps:

1. Create a session connection to Chrome Devtool:

DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();

2. Specify necessary parameters to stimulate different network condition:

devTools.send(Network.enable(Optional.of(1048576), Optional.of(524288), Optional.of(51200)));

As you can see Network.enable() static method requires three parameters which are both instance of java.util.Optional class includes:

+ maxTotalBufferSize: represents the maximum amount of data that can be buffered in the network stack.

+ maxResourceBufferSize: represents the maximum amount of data that can be buffered for individual resources (e.g., images, CSS files, JavaScript files, etc.).

+ maxPostDataSize: represents the maximum amount of data that can be sent in a single HTTP POST request.

=> You can specify it adapt to your requirements. In this example, I specified maxTotalBufferSize = 1048576 (~1MB),maxResourceBufferSize = 524288(~500KB) maxPostDataSize = 51200 (~500KB).

If you do not know how to set this params, you can also leave it empty:

devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

3. To change network condition, you will need to pass parameters to emulateNetworkConditions() static method. As below, I specify network latency is 2000ms (RTT – round-time trip) with download and upload throughput is only 40Kbs. It is quite relevant to network speed of “Slow 3G”.

devTools.send(Network.emulateNetworkConditions(
        false,
        2000,
        40 * 1024,
        40 * 1024,
        Optional.of(ConnectionType.CELLULAR2G)
));
  • Note: When import Network and ConnectionType class, you should import corresponding to your Chrome browser version. As I am using Chrome version 111, I should choose import devtools.v111.network.Network and devtools.v111.network.model.ConnectionType.
import org.openqa.selenium.devtools.v111.network.Network;
import org.openqa.selenium.devtools.v111.network.model.ConnectionType;

4. Lastly, you should close connection to DevTools with this:

devTools.close();

Run this code and watch logged time in console:

Seconds to run in throttled network

=> As you can see, it now takes ~17 seconds to finish running. It is much slower comparing to normal network condition.

Full code as below:

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v111.network.Network;
import org.openqa.selenium.devtools.v111.network.model.ConnectionType;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

public class StimulateNetworkThrottle {

    public static void main(String[] args) throws InterruptedException {

        // create Chrome driver instance
        WebDriver driver = WebDriverManager.chromedriver().create();

        // create a session of connection to Chrome devtool protocol
        DevTools devTools = ((HasDevTools) driver).getDevTools();
        devTools.createSession();

        // specify necessary params for stimulate different network condition
        devTools.send(Network.enable(Optional.of(1048576), Optional.of(524288), Optional.of(51200)));
//        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
        devTools.send(Network.emulateNetworkConditions(
                false,
                2000,
                40 * 1024,
                40 * 1024,
                Optional.of(ConnectionType.CELLULAR2G)
        ));

        // get current time in specific format and print out start time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("Start = " + LocalDateTime.now().format(formatter));

        // redirect to specific URL
        driver.get("https://ericsson.com");
        driver.manage().window().maximize();

        // print out end time to calculate total amount of time extends because of network throttling
        System.out.println("End = " + LocalDateTime.now().format(formatter));

        // close connection to devTool
        devTools.close();

        //close browser and quit driver
        driver.quit();
    }
}

Conclusion

As my experience, there are not many situations that you need to emulate network throttling for your automated test scripts. But know how and when to apply it is still quite helpful though. Thanks for reading. If you have interest with how to emulate network throttling for Playwright too, you can refer to this article.

1 thought on “Stimulate Network Throttling in Selenium (Java)”

  1. Pingback: Stimulate network throttling in Playwright (Typescript/JavaScript) - tomatoqa.com

Ask me anything