0
0
Selenium Javatesting~15 mins

Performance metrics via DevTools in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Measure page load performance metrics using Chrome DevTools Protocol in Selenium
Preconditions (3)
Step 1: Launch Chrome browser with Selenium WebDriver
Step 2: Enable Chrome DevTools Protocol (CDP) session
Step 3: Navigate to the URL 'https://example.com'
Step 4: Use CDP to collect performance metrics after page load
Step 5: Extract metrics such as First Contentful Paint, DOMContentLoaded, and Load event
Step 6: Verify that these metrics are present and have reasonable numeric values
✅ Expected Result: Performance metrics are successfully collected via DevTools and contain valid numeric values indicating page load timings.
Automation Requirements - Selenium WebDriver with Chrome DevTools Protocol (CDP) support in Java
Assertions Needed:
Assert that performance metrics map contains keys for 'FirstContentfulPaint', 'DomContentLoaded', and 'LoadEvent'
Assert that the metric values are greater than zero
Best Practices:
Use Chrome DevTools Protocol commands via Selenium's DevTools interface
Use explicit waits to ensure page load is complete before collecting metrics
Use meaningful assertions to validate metric presence and values
Close browser session properly after test
Automated Solution
Selenium Java
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v115.performance.Performance;
import org.openqa.selenium.devtools.v115.performance.model.Metric;
import org.openqa.selenium.devtools.v115.page.Page;
import org.openqa.selenium.devtools.v115.page.model.LifecycleEvent;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedCondition;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PerformanceMetricsTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        ChromeOptions options = new ChromeOptions();
        ChromeDriver driver = new ChromeDriver(options);

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

        // Enable performance domain
        devTools.send(Performance.enable());

        // Navigate to the page
        driver.get("https://example.com");

        // Wait for load event fired
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(webDriver -> {
            List<LifecycleEvent> lifecycleEvents = devTools.send(Page.getLifecycleEvents());
            return lifecycleEvents.stream().anyMatch(e -> e.getName().equals("load"));
        });

        // Get performance metrics
        List<Metric> metrics = devTools.send(Performance.getMetrics());

        // Convert list to map for easy lookup
        Map<String, Double> metricsMap = metrics.stream()
                .collect(Collectors.toMap(Metric::getName, Metric::getValue));

        // Assertions
        if (!metricsMap.containsKey("FirstContentfulPaint")) {
            throw new AssertionError("Missing FirstContentfulPaint metric");
        }
        if (!metricsMap.containsKey("DomContentLoaded")) {
            throw new AssertionError("Missing DomContentLoaded metric");
        }
        if (!metricsMap.containsKey("LoadEvent")) {
            throw new AssertionError("Missing LoadEvent metric");
        }

        if (metricsMap.get("FirstContentfulPaint") <= 0) {
            throw new AssertionError("FirstContentfulPaint metric value is not greater than zero");
        }
        if (metricsMap.get("DomContentLoaded") <= 0) {
            throw new AssertionError("DomContentLoaded metric value is not greater than zero");
        }
        if (metricsMap.get("LoadEvent") <= 0) {
            throw new AssertionError("LoadEvent metric value is not greater than zero");
        }

        System.out.println("Performance metrics collected successfully:");
        System.out.println(metricsMap);

        driver.quit();
    }
}

This Java Selenium test uses ChromeDriver and the Chrome DevTools Protocol (CDP) to collect performance metrics.

First, it sets up ChromeDriver and creates a DevTools session.

It enables the Performance domain to access performance metrics.

Then it navigates to the target URL and waits explicitly for the page load event to ensure the page is fully loaded.

After that, it collects the performance metrics and converts them into a map for easy access.

The test asserts that key metrics like FirstContentfulPaint, DomContentLoaded, and LoadEvent exist and have values greater than zero, indicating valid timings.

Finally, it prints the metrics and closes the browser.

This approach uses explicit waits and CDP commands properly, following best practices for reliable and maintainable test automation.

Common Mistakes - 4 Pitfalls
Not enabling the Performance domain before requesting metrics
Using Thread.sleep() instead of explicit waits for page load
Not checking if metrics keys exist before accessing values
Hardcoding chromedriver path without flexibility
Bonus Challenge

Now add data-driven testing to collect performance metrics for three different URLs: 'https://example.com', 'https://wikipedia.org', and 'https://github.com'.

Show Hint