string包含在Laravel Log外观中应匹配的参数 [英] stringContains argument matching within Laravel Log facade shouldReceive

查看:70
本文介绍了string包含在Laravel Log外观中应匹配的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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文档中看到了灵活的参数匹配可能是这样的:$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:

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

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

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

P.S. I've also tried ->with(\PHPUnit\Framework\Assert::stringContains('Contact does not exist')).

推荐答案

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

这篇关于string包含在Laravel Log外观中应匹配的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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