'PHPUnit - REST API testing


I have REST API written in php, i want to test it with phpunit.

I wrote test like this, it works but response body was empty. I tested it with fiddler, it send response body.

Sorry for my english.

class ProgrammerControllerTest extends PHPUnit_Framework_TestCase

{
    public function testPOST()
    {   

    // create our http client (Guzzle)
    $client = new Guzzle\Http\Client();
    $response = $client->post("http://api.loc/v2/", array(
    'headers' => "User-Agent: Fiddler\r\n" .
                "Host: api.loc\r\n".
                "Content-Type: application/x-www-form-urlencoded\r\n".
                "Content-Length: 34\r\n",
    'body'    => array('kle' =>'sino','lat' => '41', 'long' => '69'),
    ));
    var_dump($response);


    }
} 


Solution 1:[1]

You can use built in method call of Laravel to test your controllers.

$response = $this->call('POST', '/api/v1.0/pages', $parameters);
$data = $response->getData();

Your ProgrammerControllerTest should extend from TestCase

Solution 2:[2]

Can you try with

var_dump($response->getBody()->getContents());

this is my snippet ( it's in Get but it's the same )

$client = new GuzzleHttp\Client();
$response = $client->get('http://192.168.99.100/v1/hello');
var_dump($response->getBody()->getContents());

result:

string(13) "{"bar":"foo"}"

Solution 3:[3]

I know Amazon uses Guzzle to test AWS SDK, you can read more info at http://guzzle3.readthedocs.org/testing/unit-testing.html

And also, don't hesitate to dig what others are using (such as Amazon, Facebook etc...), thats why open-source is so great!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Farid Movsumov
Solution 2 Barno
Solution 3 Thomas Decaux