【发布时间】:2018-07-30 02:36:06
【问题描述】:
我正在尝试了解有关测试的更多信息,但不幸的是我必须在 Magento 1.9 中进行。* :)
考虑以下代码(GDPR 相关)...
class Vendor_Module_Helper_Data
{
public function __construct()
{
$this->config = Mage::helper('vendor_module/config');
}
public function anonymizeEmail(Mage_Customer_Model_Customer $customer)
{
return preg_replace_callback('#{([a-z_]*)}#', function ($matches) use ($customer) {
return strtolower($customer->getData($matches[1]));
}, $this->config->getEmailFormat());
}
}
class Vendor_Module_Helper_Config
{
public function getEmailFormat()
{
return Mage::getStoreConfig('vendor_module/email/format));
}
}
我正在编写一个测试,断言给客户的电子邮件格式正确,如下所示:
public function it_anonymizes_customer_email()
{
$customer = Mage::getModel('customer/customer')
->setEntityId(1)
->setFirstname('Customer')
->setLastname('Anonymous');
$configStub = $this->createMock(Vendor_Module_Helper_Config::class);
$configStub->method('getEmailFormat')
->willReturn('customer.{entity_id}@anonymo.us');
$email = Mage::helper('vendor_module')->anonymizeEmail($customer);
$this->assertEquals($email, 'customer.1@anonymo.us');
}
当然这不会按原样工作,但应该清楚我在这里尝试实现的目标......
我的问题是如何在不使用 Magento 所缺乏的 DI 的情况下使这项工作发挥最佳效果。
有没有办法模拟在另一个类的构造函数中实例化(保护)的类?这是最佳做法吗?
或者这是一个有效的解决方案:
class Vendor_Module_Helper_Data
{
public function __construct($args)
{
$this->config = isset($args['config'] ? $args['config'] : Mage::helper('vendor_module/config');
}
}
然后在测试中:
$email = Mage::helper('vendor_module', ['config' => $configStub])->anonymizeEmail($customer);
我必须将类从 Helper 更改为 Model,因为 helper 不接受构造函数参数(我认为)。
一些建议将不胜感激!
【问题讨论】:
标签: dependency-injection mocking phpunit magento-1.9