简体   繁体   中英

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);


    }
} 

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

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"}"

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM