4

有没有办法测试 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());
4

1 回答 1

13

在客户帐户控制器中 login 和 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 模型,所以在命令行中会产生错误。

真诚的,伊万

于 2012-07-31T12:28:38.667 回答