Network Interception

Mocking an API Response

How does the ShopEase product page look when the reviews API fails? You cannot ask the backend team to break QA. With NetworkInterceptor the test returns a fake response for matching requests.

import org.openqa.selenium.devtools.NetworkInterceptor;
import org.openqa.selenium.remote.http.*;

try (NetworkInterceptor interceptor = new NetworkInterceptor(driver,
        Route.matching(req -> req.getUri().contains("/api/reviews"))
             .to(() -> req -> new HttpResponse()
                     .setStatus(500)
                     .addHeader("Content-Type", "application/json")
                     .setContent(Contents.utf8String("{\"error\":\"reviews down\"}"))))) {

    driver.get("https://shopease.example.com/products/boat-rockerz-450");
    String msg = driver.findElement(By.cssSelector(".reviews .error-message")).getText();
    Assert.assertEquals(msg, "Reviews are not available right now");
    Assert.assertTrue(driver.findElement(By.id("add-to-cart")).isEnabled(), "buying must still work");
}

Example

mvn test -Dtest=ProductPageResilienceTest

Example output

[INFO] Running com.shopease.tests.ProductPageResilienceTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.877 s
[INFO] BUILD SUCCESS

How Route Matching Works

Example

The interceptor checks every request against a predicate and either mocks it or lets it through. The same idea in plain Java:

import java.util.*;
import java.util.function.*;

public class Main {
    record Response(int status, String body) {}

    public static void main(String[] args) {
        Predicate<String> isReviewsApi = url -> url.contains("/api/reviews");
        Function<String, Response> mock = url -> new Response(500, "{\"error\":\"reviews down\"}");
        Function<String, Response> realServer = url -> new Response(200, "(real response)");

        List<String> pageRequests = List.of(
                "https://shopease.example.com/products/boat-rockerz-450",
                "https://shopease.example.com/api/products/450",
                "https://shopease.example.com/api/reviews?product=450",
                "https://cdn.shopease.example.com/img/450.webp");

        for (String url : pageRequests) {
            Response r = isReviewsApi.test(url) ? mock.apply(url) : realServer.apply(url);
            System.out.println(r.status() + "  " + url.replace("https://", "") + (r.status() == 500 ? "  <- mocked " + r.body() : ""));
        }
    }
}

Output

200  shopease.example.com/products/boat-rockerz-450
200  shopease.example.com/api/products/450
500  shopease.example.com/api/reviews?product=450  <- mocked {"error":"reviews down"}
200  cdn.shopease.example.com/img/450.webp

Blocking Third-Party Scripts

Tip: Analytics and chat widgets slow tests down and sometimes cover buttons. Route requests to known third-party hosts to an empty 200 response to make pages load faster and more predictably in QA.