Test Overview
This test uses Selenium with Chrome DevTools Protocol (CDP) to intercept network requests. It verifies that a specific API call is made and checks its response status.
This test uses Selenium with Chrome DevTools Protocol (CDP) to intercept network requests. It verifies that a specific API call is made and checks its response status.
import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.devtools.DevTools; import org.openqa.selenium.devtools.v114.network.Network; import org.openqa.selenium.devtools.v114.network.model.Response; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; public class NetworkInterceptionTest { private ChromeDriver driver; private DevTools devTools; private AtomicBoolean apiCallMade; @BeforeClass public void setUp() { driver = new ChromeDriver(); devTools = driver.getDevTools(); devTools.createSession(); apiCallMade = new AtomicBoolean(false); devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty())); devTools.addListener(Network.responseReceived(), responseReceived -> { Response response = responseReceived.getResponse(); if (response.getUrl().contains("/api/data")) { if (response.getStatus() == 200) { apiCallMade.set(true); } } }); } @Test public void testApiCallIsMade() { driver.get("https://example.com"); driver.findElement(By.id("loadDataBtn")).click(); // Wait briefly to allow network events to be captured try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Assert.assertTrue(apiCallMade.get(), "Expected API call to /api/data was not made or did not return 200 status."); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and ChromeDriver launches browser | Browser window opens with DevTools session created and network interception enabled | - | PASS |
| 2 | Navigates to https://example.com | Page loads with a button having id 'loadDataBtn' visible | - | PASS |
| 3 | Finds element with id 'loadDataBtn' and clicks it | Button clicked, triggering network requests | - | PASS |
| 4 | Waits 2 seconds to capture network events | Network events captured including response for /api/data | Checks if response for /api/data has status 200 | PASS |
| 5 | Asserts that API call to /api/data was made and returned 200 | Assertion verifies apiCallMade is true | Assert.assertTrue(apiCallMade.get()) | PASS |
| 6 | Test ends and browser closes | Browser window closes | - | PASS |