我有这个 foo() 方法,我需要在 Magento 中为此方法 testFoo() 添加单元测试用例。但无法模拟 Mage::getSingleton('checkout/cart')。
来源方法
public function foo() { return Mage::getSingleton('checkout/cart')->getQuote()->getFunctionName(); }
测试功能
public function testFoo(): void { //$this->className :: Project_Catalog_Helper_Test $expected = 'string'; $this->className->method('getSingleton')->willReturn($this->cart); $this->cart->method('getQuote')->willReturn($this->cart); $this->cart->method('getFunctionName')->willReturn('string'); $this->assertEquals( $this->className->foo(), $expected ); }
当我运行时,php-unit 收到此错误日志。
MacBook-Pro % ./vendor/bin/phpunit tests/src/app/code/local/project/Catalog/Helper/OrderTest.php PHPUnit 6.5.14 by Sebastian Bergmann and contributors. Runtime: PHP 7.3.11 Configuration: /project_path/phpunit.xml.dist E 1 / 1 (100%) Time: 150 ms, Memory: 8.00MB There was 1 error: 1) Project_Catalog_Helper_Test::testFoo Error: Call to a member function getCode() on bool /project_path/app/code/core/Mage/Customer/Model/Session.php:103 /project_path/app/code/core/Mage/Core/Model/Config.php:1394 /project_path/app/Mage.php:517 /project_path/app/Mage.php:531 /project_path/app/code/community/Checkout/Model/Cart.php:20 /project_path/app/code/local/project/Catalog/Helper/Order.php:21 /project_path/tests/src/app/code/local/project/Catalog/Helper/OrderTest.php:100 /project_path/vendor/phpunit/phpunit/phpunit:53
需要一些解决方案,如何模拟 Mage::getSingleton('checkout/cart')。
注意:我无法更改 main 方法,因为它是遗留代码。只需添加单元测试用例。
您不能模拟
Mage::getSingleton('checkout/cart')
,因为它是全局命名空间中的静态函数。但是,您可以使用元编程注入结账卡模拟来注入模拟。然后在该位置恢复原来的单例。
与继承自 EComDev Testsuite 的现有问答进行比较,该问答应该具有更多指针如何使用 PHP Reflection 处理内部结构。