Last active
January 30, 2025 08:59
-
-
Save up1/f9d502b2ba739955140468a0323efa89 to your computer and use it in GitHub Desktop.
Selenium WebDriver BiDi + Network intercepter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SeleniumWithNetworkInterceptorTest { | |
static WebDriver driver; | |
@BeforeAll | |
public static void initial() { | |
System.setProperty("webdriver.chrome.driver", "path-to-driver"); | |
var options = new ChromeOptions(); | |
// Enable BiDi | |
options.setCapability("webSocketUrl", true); | |
driver = new ChromeDriver(options); | |
} | |
@AfterAll | |
public static void cleanAll() { | |
driver.quit(); | |
} | |
@Test | |
@DisplayName("ทำการจำลองข้อมูลการเรียกใช้งาน API ด้วย Selenium WebDriver BiDi") | |
public void interceptRequests() throws InterruptedException { | |
AtomicBoolean completed = new AtomicBoolean(false); | |
try (NetworkInterceptor ignored = new NetworkInterceptor(driver, (Filter) next -> req -> { | |
var res = next.execute(req); | |
if (req.getUri().contains("https://demo-backend-nodejs.vercel.app/")) { | |
res = new HttpResponse().setStatus(200) | |
// Allow CORS | |
.addHeader("Access-Control-Allow-Origin", "*") | |
.addHeader("Content-Type", MediaType.JSON_UTF_8.toString()) | |
.setContent(Contents.utf8String("{\"message\":\"Mock Hello World!\"}")); | |
} | |
completed.set(true); | |
return res; | |
})) { | |
driver.get("https://demo-frontend-reactjs.vercel.app/"); | |
Thread.sleep(2000); | |
} | |
assertTrue(completed.get()); | |
assertEquals("Mock Hello World!", driver.findElement(By.xpath("//*[@data-testid=\"message_box\"]")).getText()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment