Playwright + Java · Lesson 32 of 38

0/38 done

Module 32: Network Interception & Mocking

32. Network Interception, Mock Responses & Fault Injection

18 minlesson

Your task

Implement mockEmptySearchResults:

  1. Accept Page page and String endpointPattern.
  2. Intercept via page.route and fulfill with status 200, contentType "application/json", and body "[]".

Write it in the editor, then press Check answer (Ctrl + Enter).

Mocking Backend APIs with page.route

java
// Mock 500 internal server error on checkout:
page.route("**/api/checkout", route -> {
    route.fulfill(new Route.FulfillOptions()
        .setStatus(500)
        .setContentType("application/json")
        .setBody("{"error": "Payment gateway unavailable"}"));
});

// Abort third-party tracking scripts to speed up tests:
page.route("**/*analytics.js", Route::abort);

// Modify response headers:
page.route("**/api/user", route -> {
    route.resume(); // Pass through normally
});

Key Takeaways & Walkthrough Summary

Testing error states like 500 server errors or payment gateway timeouts is notoriously difficult in staging environments. With Playwright's page.route(), you intercept network requests on the fly and fulfill them with mocked JSON. Let's master network mocking!

Part of the Playwright + Java course (Playwright with Java). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Does page.route() mock requests for all tabs?

page.route() mocks only for that specific page. To mock across all tabs and contexts, use browserContext.route().

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip