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

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

我有这样的功能:

// $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()

我在这里错过了什么?我觉得我好像误解了一些关于嘲笑的根本性。

php laravel mocking laravel-5.4 mockery
1个回答
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()

© www.soinside.com 2019 - 2024. All rights reserved.