我想測試使用安全組件的控制器方法(添加,編輯...)。CakePHP - 控制器測試失敗,因爲安全組件
ContactsController
public function initialize() {
$this->loadComponent('Security');
}
public function add() {
$contact = $this->Contacts->newEntity();
if ($this->request->is('post')) {
$contact = $this->Contacts->patchEntity($contact, $this->request->data);
if ($this->Contacts->save($contact)) {
$this->Flash->success(__d('contact_manager', 'The contact has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__d('contact_manager', 'The contact could not be saved. Please, try again.'));
}
}
$this->set(compact('contact'));
$this->set('_serialize', ['contact']);
}
ContactsControllerTest
public function testAdd() {
$data = $this->_getData();
$this->post('/contacts/add', $data);
$this->assertResponseSuccess();
$query = $this->Contacts->find()->where([
'Profiles.lastname' => $data['profile']['lastname'],
'Profiles.firstname' => $data['profile']['firstname']
]);
$this->assertEquals(1, $query->count());
}
protected function _getData() {
$data = [
'id' => '',
'organization_id' => 2,
'profile_id' => '',
'profile' => [
'lastname' => 'Demo',
'firstname' => 'Demo',
'gender' => 'f',
'birthday' => '1990-05-20',
'email' => '[email protected]',
'phone' => '0102030405',
'phone_mobile' => '0607080900'
]
];
return $data;
}
testAdd()
總是失敗,因爲請求是黑色帶孔(與 '驗證' 指標),但在瀏覽器add()
效果很好。
我已經添加了'_Token'場與'$ data'的子項,所以'$ data'包含嚴格相同的密鑰生成的表單。但'testAdd()'再次失敗('auth'blackhole)。 – iamsaloc
@Lacos然後我建議你做一些調試,把你自己陷入安全組件,檢查它在哪裏放棄,它檢索的值是什麼,生成的比較哈希與傳遞的哈希相比是什麼樣的。我從這裏做的真的不多。 – ndm
非常感謝。 我的測試總是因爲用於生成令牌的當前請求URL而失敗。如果我在控制檯(/ contacts/add)中啓動我的測試,並且在瀏覽器中使用表單(/ myapp/contacts/add),則此URL不相同。 – iamsaloc