1

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?

Carles
  • 180
  • 2
  • 12
  • Strictly speaking, you don't really mock services for functional testing. Mocking is for unit testing. However, you can create a services_test.yaml file and define a service strictly for testing. It's all in the docs. – Cerad May 04 '20 at 17:25
  • Check this link, https://stackoverflow.com/questions/19726281/how-to-mock-symfony-2-service-in-a-functional-test – Mohammad.Kaab May 06 '20 at 21:35

1 Answers1

-1

You don't need that for functional tests. Functional testing means that you want to check "application scenario" under test, you gave input and you expecting some output behavior.

What you need here (if you want to use mock) is unit test for MyService class where you should mock injected classes.

kamil.w
  • 134
  • 1
  • 5