stringContains 参数匹配 Laravel Log 门面 shouldReceive [英] stringContains argument matching within Laravel Log facade shouldReceive

查看:32
本文介绍了stringContains 参数匹配 Laravel Log 门面 shouldReceive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw in the Laravel docs that it's possible to set a test expectation like this:

Cache::shouldReceive('get')
                ->once()
                ->with('key')
                ->andReturn('value');

然后我在 PHPunit docs 中看到了灵活的参数匹配可能是这样的:$this->stringContains('Something').

Then I saw in the PHPunit docs that flexible argument matching is possible like this: $this->stringContains('Something').

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

But when I edit my test to have this:

Log::shouldReceive('error')
            ->once();
            ->with($this->stringContains('Contact does not exist'));

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

...then I get the following error:

MockeryExceptionNoMatchingExpectationException: 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 中使用灵活的参数匹配)?

How can I accomplish my goal (with flexible argument matching within Log::shouldReceive)?

附:我也试过 ->with(PHPUnitFrameworkAssert::stringContains('Contact does not exist')).

推荐答案

外观的模拟功能使用 Mockery 来生成模拟对象.stringContains() 是 PHPUnit 模拟对象提供的功能.这两个不兼容.

The mocking functionality of facades uses Mockery to generate mock objects. stringContains() is functionality provided by PHPUnit mock objects. These two are not compatible.

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

You will need to use argument validation methods provided by Mockery.

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

My first attempt would be to use the Mockery::pattern() matcher which uses regular expressions:

Log::shouldReceive('error')
    ->once();
    ->with(Mockery::pattern('/Contact does not exist/'));

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

Another option would be to use the Mockery::on() matcher, which allows you to use a Closure to provide complex argument matching logic.

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

这篇关于stringContains 参数匹配 Laravel Log 门面 shouldReceive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆