Mockery - 公共内部调用方法的部分模拟不起作用

问题描述 投票:0回答:1

我无法模拟在另一个方法“remove”内部调用的类的公共方法“subtract”(这是示例代码,但存在相同的问题)。

public class Inventory {
    public function substract(int $value, int $change)
    {
        return $value-$change;
    }

    public function remove(int $value)
    {
        return $this->substract($value, 1);
    }
}

$mock = \Mockery::mock(Inventory::class)->makePartial();
$mock->shouldReceive('substract')->andReturn(0);
dd($mock->remove(10)); // It return 9 instead of 0

但是如果我调用 $mock->substract...我得到 0,看起来内部调用不是mock。

有人已经编码了这个问题?

php testing mockery
1个回答
0
投票

我猜你的设置有问题。 您的代码是正确的。

<?php

namespace utils;

class Inventory
{
    public function substract(int $value, int $change)
    {
        return $value - $change;
    }

    public function remove(int $value)
    {
        return $this->substract($value, 1);
    }
}

然后:

<?php

declare(strict_types=1);

namespace tests\app\extra;

use Mockery\Adapter\Phpunit\MockeryTestCase;
use utils\Inventory;

/**
 * @internal
 *
 * @coversNothing
 */
class InventoryTest extends MockeryTestCase
{
    public function testRemoveMethod()
    {
        $mock = \Mockery::mock(Inventory::class)->makePartial();
        $mock->shouldReceive('substract')->andReturn(0);
        $result = $mock->remove(10);
        $this->assertEquals(0, $result);
    }
}

回报:

$ composer test-target tests/app/extra/InventoryTest.php
> rm -rf .phpunit.result.cache || true 'tests/app/extra/InventoryTest.php'
> vendor/phpunit/phpunit/phpunit --color=always --verbose --testdox  'tests/app/extra/InventoryTest.php'
PHPUnit 9.6.19 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.4.33
Configuration: /usr/share/nginx/sites/nfs/phpunit.xml.dist

Inventory (tests\app\extra\Inventory)
 ✔ Remove method  2460 ms

Time: 00:02.461, Memory: 4.00 MB

OK (1 test, 1 assertion)
© www.soinside.com 2019 - 2024. All rights reserved.