如何在另一个调用的函数上使用shouldReceive?

时间:2019-03-30 06:36:18

标签: php laravel mocking laravel-5.4 mockery

我具有类似的功能:

// $value could be an array or SomeClass type
public function foo($key, $value) 
{
    // some code
    if ($value instanceof SomeClass) {
        $value = $this->bar($value);
    }
    // some code
}

protected function bar(SomeClass $value) 
{
    // do stuff
}

现在在我的测试中,我有这样的东西:

{
    $suppliedValue = [];

    $mock = ... // create mock
    $mock->shouldReceive('foo')->withArgs(
        // first arg should be an int or string
        // second arg should be an array or SomeClass object
    );

    if (typeOf($suppliedValue) === 'array') {
        $mock->shouldNotReceive('bar');
    } else {
        $mock->shouldReceive('bar');
    }

    $mock->aFunctionThatCallsFoo($suppliedValue);
}

无论它似乎什么都不起作用,无论向foo()提供什么值,它都不会触发shouldReceive()上的shouldNotReceive() / bar()

我在这里想念什么?我感觉好像是在误解有关模拟的基本知识。

1 个答案:

答案 0 :(得分:0)

我没有找到通过模拟解决此问题的方法,但我改用了Spy


$spy = Mockery::spy(TheClass::class)
              ->makePartial()
              ->shouldAllowMockingProtectedMethods();

$spy->aFunctionThatCallsFoo($suppliedValue);
$spy->shouldHaveReceived('foo')
    ->withArgs(/* args */); 
$spy->shouldHaveReceived('bar');

我最终创建了2个测试函数,而不是将if else用于$suppliedValue类型,其中另一个调用了shouldNotHaveReceived()