加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 是否有Laravel测试事件被触发的次数?

发布时间:2020-12-14 19:44:35 所属栏目:大数据 来源:网络整理
导读:我使用基本 PHPUnit配置文件与默认的TestCase.php文件. 我正在寻找一种方法来检查在测试期间是否多次触发事件.当前代码如下: function test_fires_multiple_events(){ $this-expectsEvents(SomeEvent::class);} 理想情况下,我想要: function test_fires_mu
我使用基本 PHPUnit配置文件与默认的TestCase.php文件.

我正在寻找一种方法来检查在测试期间是否多次触发事件.当前代码如下:

function test_fires_multiple_events()
{
    $this->expectsEvents(SomeEvent::class);
}

理想情况下,我想要:

function test_fires_multiple_events()
{
    $this->expectsEvents(SomeEvent::class)->times(3);
}

解决方法

在浏览了MocksApplicationServices中的代码之后,我能够捎带特征,以及在使用withoutEvents()方法时捕获的字段.

扩展名如下:

function test_fires_multiple_events()
{
    $this->withoutEvents(); // From MocksApplicationServices

    $c = collect($this->firedEvents)
                ->groupBy(function($item,$key) { return get_class($item); })
                ->map(function($item,$key) { return $item->count(); });

    $this->assertsEqual(3,$c->get(SomeEvent::class));

}

要逐步完成集合的操作:

1)collect($this-> firedEvents):获取捕获的事件并将它们存储在集合中.值得注意的是,MocksApplicationServices将每个事件都推送到一个数组中,这意味着它已经保持计数.

2)groupBy(function($item,$key){return get_class($item);}):按类名称分组,这意味着我们现在有一个数组集合.

3)map(函数($item,$key){..}:简单地计算孩子们.

这导致了如下结构:

IlluminateSupportCollection (1) (
    protected items -> array (2) [
        'AppEventsSomeEvent' => integer 2
        'AppEventsSomeOtherEvent' => integer 1
    ]
)

编辑
只是为了清理一下 – 您可以将以下内容添加到基本测试用例文件中:

public function assertEventFiredTimes($event,$count)
{
    $this->assertEquals(
        count(collect($this->firedEvents)
            ->groupBy(function($item,$key) { return get_class($item); })
            ->get($event,[])),$count
    );
}

然后在你的测试中:

$this->assertEventFiredTimes(SomeEvent::class,3);

不要忘记添加withoutEvents().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读