我有這個(gè) foo() 方法,我需要在 Magento 中為此方法 testFoo() 新增單元測(cè)試案例。但無法模擬 Mage::getSingleton('checkout/cart')。
來源方法
public function foo() { return Mage::getSingleton('checkout/cart')->getQuote()->getFunctionName(); }
測(cè)試功能
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 ); }
當(dāng)我運(yùn)行時(shí),php-unit 收到此錯(cuò)誤日誌。
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 方法,因?yàn)樗沁z留程式碼。只需新增單元測(cè)試用例。
您無法模擬 Mage::getSingleton('checkout/cart')
,因?yàn)樗侨蛎臻g中的靜態(tài)函數(shù)。
但是,您可以使用元程式設(shè)計(jì)注入結(jié)帳卡模擬來注入模擬。然後在該位置恢復(fù)原來的單例。
與繼承自 EComDev Testsuite 的現(xiàn)有問答進(jìn)行比較,該問答應(yīng)該具有更多指針如何使用 PHP Reflection 處理內(nèi)部結(jié)構(gòu)。