我正在使用PHPUnit测试一个类。我希望我正在测试的方法正常运行,但我想在此类中模拟另一个方法以返回特定的字符串。
我的问题是,我似乎无法创建一个模拟对象而不会覆盖我实际想要测试的方法的逻辑。
以下是正在测试的类的代码:
class Base_Customer_Model_Observer
{
public function addToVip($observer)
{
if ($this->isRequestFromVipPage() == "true")
{
$customer = $observer->getEvent()->getCustomer();
if ($customer->getGroupId() != 6)
{
$customer->setGroupId(6);
$customer->save();
Mage::getSingleton('core/session')->addSuccess('You have now been added to our VIP secret sales list');
}
else
{
Mage::getSingleton('core/session')->addSuccess('You are already on the list!');
}
}
}
private function isRequestFromVipPage() {
return Mage::app()->getRequest()->getPost('vip_list');
}
}
这是我的测试类:
class Base_Customer_Test_Model_Observer extends EcomDev_PHPUnit_Test_Case
{
public function testUserIsAddedToVipList()
{
$mock = $this->getModelMockBuilder('customer/customer')
->disableOriginalConstructor()
->setMethods(array('save'))
->getMock();
$mock->expects($this->once())
->method('setGroupId')
->with(6);
$eventObserver = new Varien_Event_Observer(array('event' => new Varien_Event(array('customer' => $mock))));
$observer = $this->getModelMockBuilder('base_customer/vip_observer')
->setMethods(array('isRequestFromVipPage', 'addToVip'))
->getMock();
$observer->expects($this->once())
->method('isRequestFromVipPage')
->will($this->returnValue('true'));
$observer->addToVip($eventObserver);
}
}
答案 0 :(得分:1)
您可以使用部分模拟(https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects),并在部分模拟上执行断言,而不是创建新的测试对象。例如:
$eventObserver = $this->getMock('Varien_Event_Observer',array('isRequestFromVipPage'), array('event' => new Varien_Event(array('customer' => $mock))))
将为您提供一个只有isRequestFromVipPage
被PHPUnit替换的对象。然后,您可以配置此方法以返回您需要的任何内容。