stringContains 在 Laravel Log 外观中匹配的参数 shouldReceive

Rya*_*yan 2 phpunit mocking laravel mockery laravel-5

我在Laravel 文档中看到可以设置这样的测试期望:

Cache::shouldReceive('get')
                ->once()
                ->with('key')
                ->andReturn('value');
Run Code Online (Sandbox Code Playgroud)

然后我在PHPunit 文档中看到灵活的参数匹配是可能的,如下所示:$this->stringContains('Something')

但是当我编辑我的测试时:

Log::shouldReceive('error')
            ->once();
            ->with($this->stringContains('Contact does not exist'));
Run Code Online (Sandbox Code Playgroud)

...然后我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现我的目标(通过灵活的参数匹配Log::shouldReceive)?

PS我也尝试过->with(\PHPUnit\Framework\Assert::stringContains('Contact does not exist'))

pat*_*cus 5

外观的模拟功能用于Mockery生成模拟对象。stringContains()是 PHPUnit 模拟对象提供的功能。这两者不兼容。

您将需要使用Mockery 提供的参数验证方法。

我的第一次尝试是使用\Mockery::pattern()使用正则表达式的匹配器:

Log::shouldReceive('error')
    ->once()
    ->with(\Mockery::pattern('/Contact does not exist/'));
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用\Mockery::on()匹配器,它允许您使用闭包来提供复杂的参数匹配逻辑。

Log::shouldReceive('error')
    ->once()
    ->with(\Mockery::on(function ($arg) {
        return stripos($arg, 'Contact does not exist') !== false;
    }));
Run Code Online (Sandbox Code Playgroud)