2014-12-07 39 views
1

我想測試我的寧靜控制器消費JSON數據。問題是我無法正確發送數據。CakePHP3集成測試和JSON數據

這是我嘗試發送數據:

$this->configRequest([ 
    'headers' => [ 
     'Accept' => 'application/json', 
     'Content-Type' => 'application/json' 
    ], 
]); 

$this->post('/api/users', "{'username':'Iason','password':'test'}"); 

debug($this->_response->body()); 

在我的控制,我檢查數據:

if (empty($this->request->data)) { 
    throw new BadRequestException("No data"); 
} 

的檢查失敗,我回來了錯誤。

如果我使用郵差測試我的API,一切工作正常。如果我嘗試以數組的形式發送數據(手冊中顯示http://book.cakephp.org/3.0/en/development/testing.html#controller-integration-testing),則控制器中也沒有任何請求數據。 我不知道我在做什麼錯。

回答

3

首先,這是無效的JSON數據,字符串必須用雙引號(")括起來,而不是單引號(')。

值可以是雙引號,數字,或true或false或null,或對象或數組中的字符串。這些結構可以嵌套。

字符串是零個或多個Unicode字符的序列,用雙引號括起來,使用反斜槓轉義符。

http://www.json.org/

的另一個問題是,非成形後的數據,即非application/x-www-form-urlencoded格式的POST體數據必須通過input選項設置:

$this->configRequest([ 
    'headers' => [ 
     'Accept' => 'application/json', 
     'Content-Type' => 'application/json' 
    ], 
    'input' => '{"username":"Iason","password":"test"}' 
]); 

$this->post('/api/users'); 

豈不如果文檔中有一個例子表明這一點,那麼就會受傷。