0

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!

1 Answer 1

2

Try sending the json as the content.

$this->call('POST', 'accounts', [], [], [], [], $accounts)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. @user3158900 can you give a brief explanation on why the format is like that? Thank you very much!
Sorry I got it now. This is because of this syntax of a function ->public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.