Symfony – Mocking a service on API functional tests

I have an API which I test it through functional tests and everything works well. The problem comes with the following situation:

I have a controller which performs an external API call through a service. I would like to mock that service during the tests, but I don’t know how to do that.

So this could be my code (as an example):

// src/service/MyService.php

class MyService
{
    public function __construct(HttpClientInterface $client) {
        $this->client = $client
    }

    public function call()
    {
        $this->client->get('https://api.com');
    }
}
// src/controller/MyController.php

class MyController
{
    /**
     * @Route("/call")
     */
    public function call(MyService $myService)
    {
        $myService->call();
    }
}
// tests/controller/MyControllerTest.php

class MyControllerTest extends WebTestCase
{
    public function testCall()
    {
        $client = static::createClient();

        $client->request('GET', '/call');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
}

How could I mock MyService service during the tests?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *