如何在 php-unit 中模拟 Mage::getSingleton('checkout/cart') ?
P粉244730625
P粉244730625 2024-04-03 13:48:23
0
1
408

我有这个 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 方法,因为它是遗留代码。只需添加单元测试用例。

P粉244730625
P粉244730625

全部回复(1)
P粉588152636

您不能模拟 Mage::getSingleton('checkout/cart'),因为它是全局命名空间中的静态函数。

但是,您可以使用元编程注入结账卡模拟来注入模拟。然后在该位置恢复原来的单例。

与继承自 EComDev Testsuite 的现有问答进行比较,该问答应该具有更多指针如何使用 PHP Reflection 处理内部结构。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!