In Selenium 4 , there is provision to intercept network by below code:
NetworkInterceptor interceptor = new NetworkInterceptor(
driver,
Route.matching(req -> true)
.to(() -> req -> new HttpResponse()
.setStatus(200)
.addHeader("Content-Type", MediaType.HTML_UTF_8.toString())
.setContent(utf8String("Creamy, delicious cheese!"))));
my question is that I never use that variable interceptor, then how or who usage it?
If you look inside NetworkInterceptor
sources:
public NetworkInterceptor(WebDriver driver, Filter filter) {
Require.nonNull("WebDriver", driver);
Require.nonNull("HTTP filter", filter);
if (!(driver instanceof HasDevTools)) {
throw new IllegalArgumentException("WebDriver instance must implement HasDevTools");
}
this.tools = ((HasDevTools) driver).getDevTools();
tools.createSessionIfThereIsNotOne();
tools.getDomains().network().interceptTrafficWith(filter);
}
you will see that when you create an object with new
it actually establishes a special kind of connection between your code and your driver:
this.tools = ((HasDevTools) driver).getDevTools();
tools.createSessionIfThereIsNotOne()
and then configures "stub" on driver side through that connection:
tools.getDomains().network().interceptTrafficWith(filter);
After that your client code does not need a reference to NetworkInterceptor
(except of closing it but since it is AutoCloseable
you should use it within try with resources
block) because all the setup already configured for WebDriver.
Also what you can pick from those sources is that the interceptor won't always works. It only works with drivers supporting DevTools such as: Chrominum, Chrome, Edge, Firefox