Search code examples
apisymfonymockingfunctional-testing

Create mocks in api functional testing with Symfony


I'm dealing with a problem I have in a Symfony 4 API functional tests. My functional tests consists in making requests to the API and analyze the response given. I've been working like this and works fine.

The problem comes with a new API method I'm implementing which needs the perform a request to an external service. I want to mock during my tests, but I don't know how can I create a mock that persists when the API receives the request from the functional test.

I've been thinking about something like create mocks which are always used in the test environment but I haven't found anything...


Solution

  • you can check in http-client service called url and if it compare your external api url return certain response, it will be look something like this:

    $guzzleServiceMock = $this
    ->getMockBuilder(GuzzleHttp\Client::class)->disableOriginalConstructor()
    ->setMethods(['get'])
    ->getMock();
    
    $guzzleServiceMock
        ->expects($this->any())
        ->method('get')
        ->with(
            $this->stringContains('/external/api/route')
        )
        ->willReturnCallback(
            function ($uri, $options = []) {
                return new Response(
                    200,
                    [],
                    '{"result": {
                        "status": "success",
                        "data": "fake data",
                    }}'
                );
            }
        );
    

    next step you will need to inject service into container, with this question you can look this repo, there are good examples of how this can be done: https://github.com/peakle/symfony-4-service-mock-examples/blob/master/tests/Util/BaseServiceTest.php