【问题标题】:How do I use shouldReceive on a function that was called by another?如何在另一个被另一个调用的函数上使用 shouldReceive?
【发布时间】:2019-08-21 01:39:59
【问题描述】:

我有这样的功能:

// $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() 提供什么值,它都不会触发bar() 上的shouldReceive() / shouldNotReceive()

我在这里缺少什么?我感觉好像我误解了关于嘲笑的一些基本原理。

【问题讨论】:

    标签: php laravel mocking laravel-5.4 mockery


    【解决方案1】:

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

    
    $spy = Mockery::spy(TheClass::class)
                  ->makePartial()
                  ->shouldAllowMockingProtectedMethods();
    
    $spy->aFunctionThatCallsFoo($suppliedValue);
    $spy->shouldHaveReceived('foo')
        ->withArgs(/* args */); 
    $spy->shouldHaveReceived('bar');
    

    我最终创建了 2 个测试函数,而不是使用 if else 来表示 $suppliedValue 的类型,而另一个调用 shouldNotHaveReceived()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2018-12-02
      • 2011-05-30
      相关资源
      最近更新 更多