Reputation: 738
Our team has created a Restful API using laravel. We are doing unit testing on the api using PHPUNIT but encountered a problem on testing a POST request.
Here is the code:
public function create_new_account()
{
$account = array (
'accountName'=>$this->fake->word,
'contactName'=>$this->fake->name,
'contactEmail'=>$this->fake->email,
'address'=>$this->fake->sentence
);
$accounts = json_encode($account);
$this->call('POST','accounts',$accounts);
$this->assertResponseOk();
}
This tests if we can create an account using API but I'm always getting an errror
1) ApiServicesTest::create_new_account
ErrorException: Argument 2 passed to Symfony\Component\HttpFoundation\Request::createRequestFromFactory() must be of the type array, string given, called in /var/www/mcx-api/vendor/symfony/http-foundation/Request.php on line 421 and defined
/var/www/mcx-api/vendor/symfony/http-foundation/Request.php:1999
/var/www/mcx-api/vendor/symfony/http-foundation/Request.php:421
/var/www/mcx-api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:775
/var/www/mcx-api/tests/ApiServicesTest.php:35
When you test the api using a client like httprequester/postman it is working fine. The api is required to be passed a JSON data so if I passed the array the api is inserting null values. But when I converted the data to json I get the error above. When I tried dd($accounts) here is the output
"{"accountName":"rerum","contactName":"Ms. Mireille Veum Jr.","contactEmail":"[email protected]","address":"Vel quidem consectetur nemo excepturi quod."}"
which means data is converted to json format and should be accepted by the api however I don't get what laravel is complaining. Can somebody point me to where I'm doing it wrong? Thank you very much!
Upvotes: 0
Views: 530
Reputation: 33058
Try sending the json as the content.
$this->call('POST', 'accounts', [], [], [], [], $accounts)
Upvotes: 2