2015-08-28 59 views
0

我們的團隊使用laravel創建了一個Restful API。我們正在使用PHPUNIT對api進行單元測試,但在測試POST請求時遇到了問題。使用PHPUnit測試Laravel中的Restful API錯誤

下面是代碼:

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

} 

此測試,如果我們可以利用API創建一個帳戶,但我總是得到一個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 

當你使用一個客戶端像測試API httprequester /郵遞員它工作正常。 api需要傳遞一個JSON數據,所以如果我傳遞數組api將插入空值。但是當我將數據轉換爲json時,我得到了上面的錯誤。當我試圖DD($賬戶)這裏是輸出

"{"accountName":"rerum","contactName":"Ms. Mireille Veum Jr.","contactEmail":"[email protected]","address":"Vel quidem consectetur nemo excepturi quod."}" 

,這意味着數據被轉換成JSON格式,應該由API所接受,但是我沒有得到什麼laravel抱怨。有人能指出我在哪裏做錯了嗎?非常感謝你!

回答

2

嘗試發送json作爲內容。

$this->call('POST', 'accounts', [], [], [], [], $accounts) 
+0

謝謝。 @ user3158900你可以簡單解釋爲什麼格式是這樣的嗎?非常感謝你! –

+0

對不起,我現在明白了。這是因爲函數的這種語法 - >公共函數調用($ method,$ uri,$ parameters = [],$ cookies = [],$ files = [],$ server = [],$ content = null) –