# TestFly Part 11: Selenium 4 CDP Network Interception & API Mocking

URL: https://hakangul.lovable.app/blog/testfly-part-11-selenium-cdp-network-interception-and-mocking
Author: Hakan Gül — Team Lead Senior Test Automation Engineer
Published: 2026-09-10
Updated: 2026-09-10
Category: test-automation
Tags: TestFly, Selenium, CDP, Mocking, Network Interception, Java, SDET

> Learn how TestFly brings Chrome DevTools Protocol (CDP) network interception, 3G/offline throttling, and API mocking to Selenium 4 in Java with zero proxy setups.

## English

**TL;DR:** While network mocking has long been considered a Playwright-only privilege, TestFly brings native Chrome DevTools Protocol (CDP) interception and network speed throttling directly to Selenium 4 in Java. SDETs can simulate offline modes, throttle connections to slow 3G, stub third-party API responses, and fail tests automatically on browser JavaScript errors with zero external proxy servers.

---

## Why Is Network Interception Critical for Modern Frontend Testing?

Modern Single Page Applications (SPAs) communicate heavily with distributed microservices, third-party payment gateways, and analytics trackers. In traditional Selenium tests:
- Testing edge cases (like a 500 Internal Server Error or a slow payment response) required manipulating backend database states or configuring clumsy proxy servers (like BrowserMob Proxy).
- Flaky tests frequently resulted from slow third-party widgets and CDN outages.
- Silent JavaScript errors in the browser console were ignored by tests unless an explicit assertion failed.

TestFly leverages Selenium 4's native CDP bridge to intercept and manipulate HTTP traffic directly at the browser process level.

---

## How to Simulate Slow 3G and Offline Modes?

Testing how your web application behaves under poor network conditions is essential for mobile-first web apps:

```java
package io.testfly.examples.network;

import io.testfly.network.NetworkSpeed;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class NetworkThrottlingTest extends BaseTest {

    @Test
    public void testOfflineBannerVisibility() {
        open("/dashboard");

        // 1. Emulate instant network disconnection
        network().emulateOffline();

        // 2. Perform action requiring network
        find("#sync-btn").click();

        // 3. Verify offline warning UI appears immediately
        assertThat(find("#offline-alert")).hasText("You are currently offline");

        // 4. Restore regular network speed
        network().resetThrottling();
    }

    @Test
    public void testSlow3GSpinnerState() {
        // Emulate realistic mobile latency: 2000ms latency, 400kbps download
        network().throttle(NetworkSpeed.SLOW_3G);

        open("/heavy-report");
        assertThat(find(".loading-spinner")).isVisible();
    }
}
```

---

## How to Mock Backend API Responses (Stubbing)?

Simulate server failures or inject custom JSON responses without touching backend environments:

```java
@Test
public void testPaymentGateway500ErrorHandling() {
    // Intercept outgoing POST requests to payment service and return HTTP 500
    network().intercept(route -> route
        .matchingUrl("**/api/v1/charge")
        .respondWith(500, "{\"error\": \"Payment processor unavailable\"}")
    );

    open("/checkout");
    find("#pay-btn").click();

    // Verify graceful error message shown to user
    assertThat(find(".error-toast")).hasText("Payment processor unavailable, please try again.");
}
```

---

## How Does TestFly Catch Silent Console Errors?

Uncaught JavaScript exceptions often break user experiences even when DOM assertions pass. TestFly's **`ConsoleErrorCollector`** monitors browser logs automatically:

```yaml title="testfly.yml"
browser:
  captureConsoleErrors: true
  failOnConsoleErrors: true # Fails the test if severe JS errors are detected
```

When a severe JavaScript error (`Uncaught TypeError`, `404 Not Found` for critical scripts) occurs, TestFly logs the error stack trace and fails the test with actionable diagnostic context.

---

## FAQ

### Does TestFly require a separate proxy server like BrowserMob?
No. TestFly interacts directly with the browser engine via the Chrome DevTools Protocol (CDP) WebSocket, requiring zero extra ports, proxies, or certificate setups.

### Does CDP network interception work with headless Chrome?
Yes. Both headful and headless Chrome/Chromium browsers fully support CDP network interception in CI/CD environments.

### Can I mock response headers and status codes?
Yes. You can override headers (e.g. `Content-Type: application/json`, CORS headers) and any HTTP status code using the fluent `respondWith()` builder.

## Türkçe

**Özet:** Ağ isteklerini engelleme ve sahte yanıtlarla besleme (mocking) uzun süre yalnızca Playwright'a özgü bir avantaj olarak görüldü. TestFly, Selenium 4'ün Chrome DevTools Protocol (CDP) yeteneklerini Java'da soyutlayarak harici proxy sunucularına gerek kalmadan yavaş ağ simülasyonu (3G / Offline), API yanıt stubbing ve otomatik konsol JavaScript hata denetimi sunar.

---

## Ağ Manipülasyonu Modern Web Testlerinde Neden Zorunludur?

Tek sayfalı modern web uygulamaları (SPA); onlarca mikroservis, ödeme ağ geçidi ve harici analitik servisiyle iletişim kurar. Geleneksel Selenium testlerinde:
- Ödeme servisinin 500 hatası vermesi gibi uç senaryoları test etmek için backend veritabanlarına müdahale etmek veya hantal proxy araçları (BrowserMob gibi) kurmak gerekirdi.
- Üçüncü parti harici servislerin gecikmesi testleri kararsız (flaky) hale getirirdi.
- Tarayıcı konsolunda patlayan JavaScript hataları, DOM'daki bir buton bozulmadığı sürece fark edilmezdi.

TestFly, Selenium 4'ün yerel CDP altyapısını kullanarak HTTP trafiğini doğrudan tarayıcı seviyesinde manipüle eder.

---

## Yavaş Bağlantı (3G) ve Çevrimdışı (Offline) Mod Nasıl Simüle Edilir?

Mobil ve zayıf bağlantı koşullarında uygulamanızın davranışını test etmek kritik önem taşır:

```java
package io.testfly.examples.network;

import io.testfly.network.NetworkSpeed;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class AgManipulasyonTesti extends BaseTest {

    @Test
    public void cevrimdisiUyariKartiGoruntulenmeli() {
        open("/dashboard");

        // 1. Ağ bağlantısını anında kes
        network().emulateOffline();

        // 2. Ağ gerektiren işlemi yap
        find("#sync-btn").click();

        // 3. Çevrimdışı uyarısını doğrula
        assertThat(find("#offline-alert")).hasText("İnternet bağlantınız koptu");

        // 4. Ağı normale döndür
        network().resetThrottling();
    }

    @Test
    public void yavas3gYuklenmeAnimasyonuGosterilmeli() {
        // Gerçekçi 3G gecikmesi: 2000ms gecikme, 400kbps indirme hızı
        network().throttle(NetworkSpeed.SLOW_3G);

        open("/raporlar");
        assertThat(find(".loading-spinner")).isVisible();
    }
}
```

---

## Arka Uç API Yanıtları Nasıl Mock'lanır (Stubbing)?

Backend servisine hiç dokunmadan belirli bir uç noktadan dönen HTTP durum kodunu veya JSON gövdesini manipüle edin:

```java
@Test
public void odemeHatasiDurumundaKullaniciUyarisi() {
    // Ödeme servisine giden POST çağrısını yakala ve 500 dön
    network().intercept(rota -> rota
        .matchingUrl("**/api/v1/charge")
        .respondWith(500, "{\"error\": \"Ödeme servisi geçici olarak hizmet dışı\"}")
    );

    open("/checkout");
    find("#pay-btn").click();

    // Kullanıcıya gösterilen hata mesajını doğrula
    assertThat(find(".error-toast")).hasText("Ödeme servisi geçici olarak hizmet dışı");
}
```

---

## Sessiz JavaScript Konsol Hataları Nasıl Yakalanır?

DOM elemanları doğru görünse bile arka planda fırlatılan kritik JavaScript hataları kullanıcı deneyimini bozar. TestFly'ın **`ConsoleErrorCollector`** modülü tarayıcı konsolunu sürekli dinler:

```yaml title="testfly.yml"
browser:
  captureConsoleErrors: true
  failOnConsoleErrors: true # Ciddi JS hatalarında testi otomatik başarısız say
```

Kritik bir hata (`Uncaught TypeError`, kayıp script dosyaları) oluştuğunda TestFly test raporuna hata yığınını ekler ve testi anında patlatır.

---

## SSS

### TestFly ağ engelleme için BrowserMob gibi harici bir proxy sunucusuna ihtiyaç duyar mı?
Hayır. TestFly doğrudan Chrome DevTools Protocol (CDP) WebSocket hattı üzerinden tarayıcı motoruyla konuşur; harici port veya sertifika kurulumu gerektirmez.

### CDP ağ manipülasyonu headless tarayıcılarda çalışır mı?
Evet. CI/CD sunucularında çalışan headless Chrome/Chromium tarayıcılar CDP protokolünü eksiksiz destekler.

### Yanıt başlıkları ve durum kodları özelleştirilebilir mi?
Evet. `respondWith()` metodu üzerinden istediğiniz HTTP durum kodunu (401, 403, 500, 503) ve JSON başlıklarını döndürebilirsiniz.
