目前我正在嘗試使用驗證組件檢索用戶標識的控制器。由於我對單元/集成測試相當陌生,因此我不知道如何使其工作。此外,所有我能找到的這個特殊問題的內容是爲CakePHP的版本編寫2.模擬驗證cakephp 3
控制器功能:
public function favorite(){
// Particular line where the problem is occurring:
$userId = $this->Auth->User()['id'];
// Get all favorite pictures of the user
$query = $this->UsersPictures->getFavoritePictures($userId);
$results = $query->all();
// Replace the link in the result set by a presigned url of Amazon
foreach($results as $result){
$result->picture->link = $this->Aws->getTokenizedItem($result->picture->link);
}
$this->set([
'success' => true,
'data' => [
'pictures' => $results
],
'_serialize' => ['success', 'data']
]);
}
集成測試:
public function testFavoriteShouldPass(){
$this->configRequest([
'headers' => [
'Accept' => 'application/json'
]
]);
$this->get('api/pictures/favorite/1.json');
$expected = [
'success' => true,
'data' => [
[
'user_id' => 1,
'picture_id' => 1,
'created' => '2016-04-03T20:35:40+0000',
'modified' => '2016-04-03T20:35:40+0000',
'picture' => [
'id' => 1,
'album_id' => 1,
'description' => 'Lorem ipsum dolor sit amet',
'link' => 'test',
'favorite' => true,
'created' => null,
'modified' => null,
'cover_photo' => true
]
]
]
];
$this->assertEquals($expected, $response);
}
我的問題是我怎麼能爲$ this-> Auth-> User()['id']插入一個默認ID爲1的用戶。
$this->_controller->Auth
->staticExpects($this->any())
->method('user')
->will($this->returnValue([
'id' => 1,
'username' => 'admin',
'created' => '2013-05-08 00:00:00',
'modified' => '2013-05-08 00:00:00',
'email' => '[email protected]',
]));
但是,我讀了staticExpects從PHPUnit的3.8版(我用5.2)棄用:我,我需要用的東西,看起來像這樣的其他問題看見。我應該如何嘲笑這個?
我想你不明白這個問題。問題是我想在測試期間爲$ this-> Auth-> User('id')分配一個固定值(例如user_id始終爲1)。通過這種方式,我可以測試控制器操作是否像應該那樣工作。 – markvdlaan93