我有這個 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 處理內部結構。