lundi 4 mai 2020

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?

Aucun commentaire:

Enregistrer un commentaire