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

标签 laravel laravel-5 mocking phpunit mockery

我在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/

相关文章:

php - 如何在移动图像时动态创建文件夹?

linux - 拉维尔 5 : Failed to open stream: Permission denied

angularjs - Laravel+Angular 项目的 Auth 和 CSRF token 在生产中不起作用

Laravel PHPUnit : how to test url prefix

go - 如何模拟 amqp.Dial 等库中的函数

python - 我应该如何在Python中使用Mocks进行测试?

php - 使用 Dropdown Laravel 中的变量填充表格

Laravel 5 - 验证当前用户密码

php - 如何在 Mac 操作系统中为 Laravel 运行 Composer 命令?

ruby - 有什么方法可以验证模拟或 stub 是否有效?