简体   繁体   中英

Phpunit testing Laravel 5.1 restful controller

I have been stuck on that issue for a little while, no other question on SO helped me.

I am using Laravel 5.1 and phpunit to test a restful controller. My testing code looks as such:

$this->post('/api/book', [ 'title' => 'my book'])
  ->assertResponseOk();

And the target controller has, among others, the following code:

Log::debug('title: ' . $request->json('title'));

ie on the testing side I expect to use the TestCase::post() method to send a request and on the server side I expect to use the Request::json() method to read from the request. However when I look at the logs I see the following empty string

[2015-10-31 17:26:01] testing.DEBUG: title:   

This is showing that either my testing code is not setting the right data in the request or that my server code is not reading the request properly. By the way, the server is failing a bit further as well, reflecting the missing title value in the logs.

I am also using a Firefox plugin, RESTClient , to manually test my web app and I had to set properly the body (using double-quotes around the title key, respecting strictly the JSON specs) to make sure the server code work. So the exact format is a trail I followed, without success so far.

So my question is, what is the most recommended code to use for a RESTful controller on the testing and on the server sides, in Laravel 5.1?

The reason your log is empty is because this call $request->json('title') actually returns an array, not a string.

https://github.com/illuminate/http/blob/master/Request.php#L552

The correct way of accessing the key is like so:

Log::debug('title: ' . $request->title);

As described here:

http://laravel.com/docs/5.1/requests#retrieving-input

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