stringContains 参数在 Laravel 内匹配 Log facade shouldReceive
stringContains argument matching within Laravel Log facade shouldReceive
我在 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
中使用灵活的参数匹配)?
P.S。我也试过 ->with(\PHPUnit\Framework\Assert::stringContains('Contact does not exist'))
.
facades 的模拟功能使用 Mockery
生成模拟对象。 stringContains()
是 PHPUnit 模拟对象提供的功能。这两个不兼容。
您将需要使用 Mockery 提供的 argument validation 方法。
我的第一次尝试是使用 \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 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
中使用灵活的参数匹配)?
P.S。我也试过 ->with(\PHPUnit\Framework\Assert::stringContains('Contact does not exist'))
.
facades 的模拟功能使用 Mockery
生成模拟对象。 stringContains()
是 PHPUnit 模拟对象提供的功能。这两个不兼容。
您将需要使用 Mockery 提供的 argument validation 方法。
我的第一次尝试是使用 \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;
}));