Zend framework 如何测试实现CSRF元素的Zend framework2表单?
我使用Zend/form创建了登录表单,它包含输入元素和CSRF元素Zend framework 如何测试实现CSRF元素的Zend framework2表单?,zend-framework,zend-framework2,phpunit,Zend Framework,Zend Framework2,Phpunit,我使用Zend/form创建了登录表单,它包含输入元素和CSRF元素 <!-- sample login.phtml code snippet --> <form method="post" action="/xyz"> <?php echo $this->formelement($form->get('email')); echo $this->formelement($form->get('password')); echo $th
<!-- sample login.phtml code snippet -->
<form method="post" action="/xyz">
<?php
echo $this->formelement($form->get('email'));
echo $this->formelement($form->get('password'));
echo $this->formelement($form->get('csrf'));
echo $this->formelement($form->get('submit'));
?>
</form>
public function testLogin()
{
//code goes here
$params = array('email' => 'example@test.com', 'password' => 'example@test.com');
$this->dispatch($url, $method, $params);
//if the given username and password is correct the login page redirected to default home page
$this->assertResponseStatusCode(302);
}
在上面的测试用例中,我设置了电子邮件和密码值,但我不知道如何设置CSRF元素。如何测试实现CSRF元素的表单?这可以通过以下方法轻松实现:
$form = new LoginForm();
$csrf = $form->get('csrf')->getValue();
$params = array('email' => 'example@test.com',
'password' => 'example@test.com',
'csrf' => $csrf
);
除非您的表单需要表单管理器,否则您将不得不使用表单管理器,而不仅仅是实例化类,但在单元测试中也很容易做到这一点
更新:
另一种有效的方法是:
$form = new LoginForm();
$form->prepare();
$params = new \Zend\Stdlib\Parameters(
array(
'csrf' => $_SESSION['Zend_Validator_Csrf_salt_csrf']['hash'],
'yourotherparams' => 'thingsandstuff'
);
$this->dispatch($url, $method, $params);
在分派指定的URL时,我如何重用实例化的表单?非常确定当您这样做时,csrf令牌将被添加到SessionContainer中,并且当您分派到urltest case仍然失败时,csrf令牌将在SessionContainer中可用!我可以知道失败的原因吗?
$\u会话['Zend\u Validator\u Csrf\u salt\u Csrf']['hash']
和$form->get('Csrf')->getValue()代码>返回相同的哈希键。您的解决方案绝对完美<代码>echo var_dump($loginForm->getMessages())当我使用您的逻辑设置CSRF时,代码>返回空数组。