vendredi 10 août 2018

Mock a Guzzle request inside Symfony2 controller

I'm creating a functional test, and I need to mock the response from a request made with Guzzle to an external API. How can I mock this request? I found examples with mocking the request itself, but I want to mock the request that is made inside another request.

Example:

I have the controller:

use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class MyController extends Controller
{
    public function indexAction(Request $request)
    {
        $response = Client()->post('http://some.url', [
            'form_params' => [
                'param1' => 'value1'
            ]
        ]);

        $result = $this->doSomethingWithTheResponse($response);
        return new JsonResponse(['status' => $result], Response::HTTP_OK);
    }
}

And I have a test class:

class MyTestClass extends WebTestCase
{
    public function testSomething()
    {
        $client = static::createClient();
        $client->request('GET', 'path_to_my_controller');
        $response = json_decode($client->getResponse()->getContent());

        $this->assertEquals($response, $expectedResponse);
    }
}

How can I mock the guzzle request inside the controller, and still use $client->request() in my test class?

Aucun commentaire:

Enregistrer un commentaire