Reputation: 31
I am not able to mock a public method 'substract' of a class who is called internally inside another method 'remove' (This is an example code but with same issue).
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
But if I call $mock->substract.... I got 0, it looks like the internal call is not mock.
Someone already code this problem ?
Upvotes: 0
Views: 53
Reputation: 199
I guess it's something wrong on your settings. Your code are correct.
<?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);
}
}
And then:
<?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);
}
}
The return:
$ 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)
Upvotes: 0