我在Laravel docs中看到可以像这样设置测试期望:
Cache::shouldReceive('get')
->once()
->with('key')
->andReturn('value');
然后我在PHPunit docs中看到了灵活的参数匹配可以像这样:$this->stringContains('Something')
。
但是当我编辑我的测试时:
Log::shouldReceive('error')
->once();
->with($this->stringContains('Contact does not exist'));
...然后我收到以下错误:
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_Illuminate_Log_Writer::error("Contact does not exist blah blah etc").
Either the method was unexpected or its arguments matched no expected argument list for this method
如何实现我的目标(通过 Log::shouldReceive
中灵活的参数匹配)?
附注我还尝试过 ->with(\PHPUnit\Framework\Assert::stringContains('联系人不存在'))
。
最佳答案
Facade 的模拟功能使用 Mockery
来生成模拟对象。 stringContains()
是 PHPUnit 模拟对象提供的功能。这两者不兼容。
您将需要使用argument validation Mockery 提供的方法。
我的第一次尝试是使用使用正则表达式的 \Mockery::pattern()
匹配器:
Log::shouldReceive('error')
->once()
->with(\Mockery::pattern('/Contact does not exist/'));
另一种选择是使用 \Mockery::on()
匹配器,它允许您使用闭包来提供复杂的参数匹配逻辑。
Log::shouldReceive('error')
->once()
->with(\Mockery::on(function ($arg) {
return stripos($arg, 'Contact does not exist') !== false;
}));
关于laravel - stringContains 在 Laravel Log 外观中匹配的参数 shouldReceive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46921877/