1

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...

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure if I understand correctly, but if you'd like to mock an external API (meaning your application is connecting to another application on another server), one solution would be to actually lunch a mock server to replace your actual external server.

Either you implement such a mock server yourself or you use an existing solution such as http://wiremock.org/

2 Comments

The problem is that I'm not testing an external API. I want to test the API which I'm currently developing but in functional tests I'm performing real requests to the API, so I don't know how to create a specific mock for a method called in my API.
@Carles If you're calling the API via client->request(), then there's nothing you can mock. You would have to make it a unit test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.