Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Guzzle Mock Handler to a PHP class to test an API call that has json response

I have a php class that uses guzzle to call an API and get a response:

public function getResponseToken()
{
    $response = $this->myGUzzleClient->request(
        'POST',
        '/token.php,
        [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'form_params' => [
                'username' => $this->params['username'],
                'password' => $this->params['password'],
            ]
        ]
    );

    return json_decode($response->getBody()->getContents())->token;
}

I am trying to test this method using guzzle mock handler, this is what I have done so far but not working:

public function testGetResponseToken()
{

    $token = 'stringtoken12345stringtoken12345stringtoken12345';
    $mockHandler = new MockHandler([
        new Response(200, ['X-Foo' => 'Bar'], $token)
        ]
    );

    $handlerStack = HandlerStack::create($mockHandler);
    $client = new Client(['handler' => $handlerStack]);


    $myService = new MyService(
            new Logger('testLogger'),
            $client,
            $this->config
        );

        $this->assertEquals($token, $myService->getResponseToken());
}

the error I am getting says "Trying to get property of non-object", so looks to me MyService is not using the handler to make the call. What am I doing wrong?

The class works as expected outside of the test context. Also note the client in normally injected in MyService from service.yml (I am using symfony).

like image 531
user3174311 Avatar asked Sep 14 '25 00:09

user3174311


1 Answers

Your handler work fine, you just mock the wrong response data. You should make the response as raw json.

Try

$token = 'stringtoken12345stringtoken12345stringtoken12345';
    $mockHandler = new MockHandler(
    [
    new Response(200, ['X-Foo' => 'Bar'], \json_encode([ 'token' => $token ]))
    ]
);

Now it should be works

like image 94
Omar Ghorbel Avatar answered Sep 15 '25 13:09

Omar Ghorbel