有没有办法测试Magento POST控制器的动作?例如。客户登录:
Mage_Customer_AccountController::loginPostAction()
我正在使用EcomDev_PHPUnit模块进行测试。它适用于基本操作,但我无法调用POST操作。
$this->getRequest()->setMethod('POST');
// ivokes loginAction instead loginPostAction
$this->dispatch('customer/account/login');
// fails also
$this->dispatch('customer/account/loginPost');
// but this assert pass
$this->assertEquals('POST', $_SERVER['REQUEST_METHOD']);
我想或多或少地进行测试
// ... some setup
$this->getRequest()->setMethod('POST');
$this->dispatch('customer/account/login');
// since login uses singleton, then...
$session = Mage::getSingleton('customer/session');
$this->assertTrue($session->isLoggedIn());
答案 0 :(得分:13)
在客户帐户控制器登录和loginPost是两个不同的操作。至于登录,你需要做这样的事情:
// Setting data for request
$this->getRequest()->setMethod('POST')
->setPost('login', array(
'username' => 'customer@email.com',
'password' => 'customer_password'
));
$this->dispatch('customer/account/loginpost'); // This will login customer via controller
但只有在需要测试登录过程时才需要这种测试体,但如果只想模拟客户登录,则可以创建特定客户登录的存根。我在少数项目中使用它。只需将此方法添加到测试用例中,然后在需要时使用。它将在单次测试运行中登录客户,然后将拆除所有会话更改。
/**
* Creates information in the session,
* that customer is logged in
*
* @param string $customerEmail
* @param string $customerPassword
* @return Mage_Customer_Model_Session|PHPUnit_Framework_MockObject_MockObject
*/
protected function createCustomerSession($customerId, $storeId = null)
{
// Create customer session mock, for making our session singleton isolated
$customerSessionMock = $this->getModelMock('customer/session', array('renewSession'));
$this->replaceByMock('singleton', 'customer/session', $customerSessionMock);
if ($storeId === null) {
$storeId = $this->app()->getAnyStoreView()->getCode();
}
$this->setCurrentStore($storeId);
$customerSessionMock->loginById($customerId);
return $customerSessionMock;
}
还在上面的代码中模拟了renewSession方法,因为它使用的是直接的setcookie函数,而不是core / cookie模型,所以在命令行中它会产生错误。
此致 伊万