在 Mockery 中为特定参数指定 return 值期望的最短方法

Shortest way to specify a return value expectation for a specific argument in Mockery

我想创建一个 Mock 方法,该方法应该 return true 用于特定参数,false 用于任何其他参数。

我可以通过以下方式实现:

$this->myMock = Mockery::mock(MyClass::class);
$this->myMock->shouldReceive('myMethod')->with('my-argument')->andReturn(true);
$this->myMock->shouldReceive('myMethod')->andReturn(false);

但我想知道是否有任何更短的方法来指定它,因为我必须为 许多 模拟执行此操作,并且看起来像很多代码用于这个简单的目的(请注意我的 properties/classes/methods/arguments 名称比这个例子要长得多)。

您可以使用 Mockery 的 andReturnUsing 方法。它需要一个闭包来通过评估提供的参数来计算 return 值。应该像这样工作:

$this->mock
    ->shouldReceive('myMethod')
    ->andReturnUsing(function ($argument) {
        if ($argument) {
            return true;
        }

        return false;
    });

我发现我可以使用:

$this->myMock = Mockery::mock(MyClass::class);
$this->myMock->shouldReceive('myMethod')->passthru();

这会将对 myMethod() 的调用推迟到真实对象,这将 return truefalse 取决于参数 - 这显然不行问题中的代码做同样的事情,但它在我的场景中确实有效,而且它更短。