【问题标题】:stringContains argument matching within Laravel Log facade shouldReceivestringContains 参数匹配 Laravel Log 门面 shouldReceive
【发布时间】:2018-04-05 22:06:21
【问题描述】:

我在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('Contact does not exist'))

【问题讨论】:

    标签: laravel laravel-5 mocking phpunit mockery


    【解决方案1】:

    外观的模拟功能使用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;
        }));
    

    【讨论】:

    • 哇,我喜欢它。非常感谢!
    • 您到argument validation 的链接对我有帮助,因为它是Mockery::withArgs() 我需要对多个参数执行验证。谢谢
    • 刚才又帮到了我。谢谢。我无法让\Mockery::pattern() 工作,但\Mockery::on() 可以。
    • 哇,我一直回到这个答案,希望我能记住这个,或者更多的文章会链接到这里。
    • @Ace pattern() 方法是在 1.0 版中添加的。如果您使用的是 0.9.11 或更低版本,pattern() 方法将不存在。
    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 2018-08-08
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多