Monday, July 20, 2026

Playwright Network Interception and API Mocking with Java (Complete Guide)

Introduction

Modern web applications communicate extensively with backend services through REST APIs. Every time you log in, search for products, submit forms, or load dashboards, your browser sends multiple HTTP requests behind the scenes.

Traditionally, UI automation relied on live backend services, making tests slow and vulnerable to network issues. Playwright changes this by allowing you to intercept network traffic, modify requests, mock responses, and even simulate server failures—all from your test code.

In this guide, you'll learn how to use Playwright's network interception and API mocking capabilities with Java to build faster, more reliable automation tests.


What is Network Interception?

Network interception allows you to inspect or control HTTP requests made by the browser during test execution.

You can:

  • Observe outgoing requests
  • Modify request headers
  • Change request payloads
  • Mock API responses
  • Abort requests
  • Simulate backend failures
  • Improve test reliability

Why Use API Mocking?

API mocking allows frontend testing even when backend services are:

  • Still under development
  • Temporarily unavailable
  • Returning inconsistent data
  • Difficult to reproduce specific scenarios
  • Rate limited

Instead of calling the real server, Playwright returns a predefined response.

Benefits include:

  • Faster execution
  • Stable tests
  • Repeatable scenarios
  • Easier edge-case testing

Understanding Playwright Routes

Playwright uses the route() method to intercept requests.

Basic syntax:

page.route("**/*", route -> {

    route.continue_();

});

This intercepts every request and allows it to continue normally.


Intercept a Specific API Request

Suppose the application calls:

GET /api/users

Intercept only that endpoint:

page.route("**/api/users", route -> {

    route.continue_();

});

Other requests continue without interception.


Block Images to Speed Up Tests

Large images increase page load time.

Block them during automation:

page.route("**/*.{png,jpg,jpeg,gif}", route -> {

    route.abort();

});

Benefits:

  • Faster execution
  • Lower bandwidth usage
  • Reduced memory consumption

Mock an API Response

Instead of calling the real server:

page.route("**/api/users", route -> {

    route.fulfill(

        new Route.FulfillOptions()

            .setStatus(200)

            .setContentType("application/json")

            .setBody("""
                [
                  {
                    "id":1,
                    "name":"John Doe"
                  }
                ]
            """)
    );

});

The application receives the mocked response immediately.


Mock an Error Response

Testing error handling is easy.

Example:

page.route("**/api/users", route -> {

    route.fulfill(

        new Route.FulfillOptions()

            .setStatus(500)

            .setBody("Internal Server Error")

    );

});

Now you can verify whether the application displays the correct error message.


Simulate Network Failure

To simulate a server outage:

page.route("**/api/users", route -> {

    route.abort();

});

This allows you to validate retry logic and offline behavior.


Modify Request Headers

You can add or replace HTTP headers.

page.route("**/api/users", route -> {

    Map<String, String> headers =
        new HashMap<>(route.request().headers());

    headers.put("X-Test-User", "Automation");

    route.resume(

        new Route.ResumeOptions()
            .setHeaders(headers)

    );

});

Useful for testing feature flags or custom authentication.


Modify POST Request Data

Intercept a request before it reaches the server.

page.route("**/api/orders", route -> {

    System.out.println(
        route.request().postData()
    );

    route.continue_();

});

This helps verify request payloads during automation.


Log Network Requests

Monitor all requests:

page.onRequest(request ->

    System.out.println(
        request.method() + " " + request.url()

    )
);

Useful for debugging complex applications.


Log Network Responses

Capture server responses:

page.onResponse(response ->

    System.out.println(

        response.status() +

        " " +

        response.url()

    )
);

This helps identify failed API calls.


Wait for a Specific Response

Instead of using delays:

page.waitForResponse(

    "**/api/users"

);

This ensures the test proceeds only after the required response is received.


Verify API Response Status

Example:

page.onResponse(response -> {

    if (response.url().contains("/users")) {

        System.out.println(

            response.status()

        );

    }

});

You can also validate response headers or body content.


Practical Scenario

Imagine an e-commerce application.

Flow:

  1. User searches for a product.
  2. Frontend calls:
/api/search
  1. Instead of calling the real backend, Playwright returns:
[
  {
    "product":"Laptop",
    "price":899
  }
]

The UI behaves exactly as if the backend had returned the data.

This approach enables testing even when backend systems are unavailable.


Best Practices

Mock Only What Is Necessary

Avoid mocking every request.

Use real backend services when integration testing is required.

Mock only external or unstable dependencies.


Keep Mock Data Realistic

Use responses that resemble production data.

Include:

  • IDs
  • Dates
  • Nested objects
  • Validation messages

This improves test quality.


Separate Mock Files

Store large mock responses in JSON files instead of embedding them in Java code.

Example:

src

└── test

    └── resources

        └── mocks

            ├── users.json

            ├── products.json

            └── orders.json

Log Requests During Debugging

Request and response logging simplifies troubleshooting.

Disable verbose logging in production pipelines unless needed.


Combine with API Tests

Use Playwright's built-in API testing features alongside network interception to create comprehensive end-to-end automation.


Common Interview Questions

What is network interception in Playwright?

Network interception allows tests to inspect, modify, block, or mock HTTP requests and responses during browser automation.


What is API mocking?

API mocking replaces real backend responses with predefined data, enabling reliable frontend testing without depending on live services.


Can Playwright block network requests?

Yes. The route.abort() method can block requests such as images, analytics scripts, or API calls.


Why use mocked APIs?

Mocked APIs make tests faster, more stable, and easier to execute when backend services are unavailable or difficult to control.


How do you wait for a specific network response?

Use page.waitForResponse() to synchronize test execution with a specific HTTP response.


Conclusion

Network interception and API mocking are among Playwright's most powerful capabilities.

They enable you to build faster, more reliable, and more maintainable automation suites by reducing dependency on external services and allowing precise control over browser communication.

In this guide, you learned how to:

  • Intercept network requests
  • Mock API responses
  • Modify headers and request payloads
  • Block unwanted resources
  • Simulate server failures
  • Wait for network responses
  • Apply enterprise best practices

Mastering these techniques will help you create robust automation frameworks capable of testing complex applications under a wide variety of real-world conditions.

No comments:

Post a Comment