MockHttpClient
In this lesson, we unit test our HRClient
class - specifically its ability to send job application data to an external HR system via HTTP.
To avoid making real network calls, we use Symfony’s powerful MockHttpClient
and MockResponse
classes, which let us simulate HTTP requests and assert on the exact details of the outgoing request.
We also pass a callback to the mock client. This gives us full control over the simulated request lifecycle, allowing us to inspect:
- The HTTP method (
POST
) - The URL (e.g.
https://hr.example.com/api/applications/create
) - The request body (JSON payload with first name, last name, etc.)
By asserting on these values inside the callback, we can ensure the correct data is being sent to the correct endpoint - all without leaving our test suite.
We also start sketching out a second test for failure handling, which we'll complete in the next lesson.
This pattern - mocking external APIs with MockHttpClient
- is a clean and reliable way to test your HTTP clients in isolation, ensuring you catch mistakes early while keeping your tests fast and network-free.
0 comments