沃梦达 / 编程问答 / php问题 / 正文

Laravel 按需测试通知

Laravel testing on demand notification(Laravel 按需测试通知)

本文介绍了Laravel 按需测试通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Slack 通知类,每次用户执行激活过程时,它都会在我们公司的 Slack 帐户中的特定频道中发送一条消息.

I have a slack notification class that sends a message inside our company slack account, in a specific channel, every time an user performs the activation process.

系统工作正常,但它是手动测试的,这并不酷.

The system works, but it's manually tested and that's not cool.

通知由附加到 UserHasBeenActivated 事件的侦听器发送,侦听器如下:

The notification is sent by a listener attached to an UserHasBeenActivated event, the listener is the following:

public function handle(UserHasBeenActivated $event)
{
    Notification::route("slack", config("services.slack.user.url"))
        ->notify(new UserActivated($event->user));
}

非常直接.这里的问题是通知是按需通知的,因此很难测试......因为没有任何关于如何测试按需通知的文档!

Pretty straight forward. The problem here is that the notification is on demand thus it's difficult to test... because there isn't any sort of documentation on how to test on demand notifications!

目前我被困在这里:

public function it_sends_a_notification_when_an_user_is_activated()
{
    Notification::fake();

    $user = factory(User::class)->states("deleted")->create();
    $user->activate();

    Notification::assertSentTo(
        $user,
        UserActivated::class
    );
}

当然这个测试失败了,activate() 方法是触发事件UserHasBeenActivated 和顺序所有的监听器,其中一个发送相应的通知.

Of course this test fails, the activate() method is what triggers the Event UserHasBeenActivated and sequentially all the listeners, and one of them sends the corresponding notification.

您知道如何测试按需通知吗?有没有我遗漏的隐藏 API?

Do you know how to test on demand Notifications? Is there any hidden API that am I missing?

推荐答案

对于新人

Laravel 在 v5.5.14 中引入了使用提供的 Notification::fake() 系统测试匿名通知的能力.

Laravel introduces in v5.5.14 the ability to test anonymous notification by using the provided Notification::fake() system.

更多关于这个功能的信息在这里:https://github.com/laravel/framework/pull/21379

More about this new feature here: https://github.com/laravel/framework/pull/21379

这篇关于Laravel 按需测试通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 按需测试通知

基础教程推荐