Как проверить Laravel Уведомление отправлено слушателем? - PullRequest
1 голос
/ 03 апреля 2020

У меня есть рабочий код, в котором при создании записи клиента отправляется событие, а затем слушатель отправляет уведомление агенту клиента.

EventServiceProvider. php

protected $listen = [
        'App\Events\CustomerCreated' => [
            'App\Listeners\TriggerExternalCustomerCreation',
            'App\Listeners\SendNotificationCustomerCreated',
        ],
]

SendNotificationCustomerCreated. php

public function handle(CustomerCreated $event)
    {
        $when = now()->addMinutes(0);
        $event->customer->manager->notify((new CustomerCreatedNotification($event->customer))->delay($when));
    }

Вот мой тестовый пример: -

public function customer_created_event_dispatch()
    {
        // $this->markTestIncomplete('This test has not been implemented yet.');
        $this->withoutExceptionHandling();
        Event::fake();
        Notification::fake();

        $user = factory(User::class)->states('order management')->create();
        $data = $this->data(['address' => true, 'contact' => true]);

        $response = $this->actingAs($user)->post(route('customers.store'), $data);
        $response->assertSessionHasNoErrors();

        $customers = Customer::all();
        $customer = $customers->first();
        $manager = $customer->manager;

        $this->assertCount(1, $customers);

        Event::assertDispatched(CustomerCreated::class, function ($event) use ($customers) {
            return $event->customer->id === $customers->first()->id;
        });

        Notification::assertSentTo(
            $manager,
            CustomerCreatedNotification::class,
            function ($notification, $channels) use ($customer) {
                return $notification->customer->id === $customer->id;
            }
        );
    }

Первоначально слушатель находится в очереди, но я пытаюсь удалить из очереди, но ошибка остается.

Я могу подтвердить, что событие отправлено, поскольку оно передало Event :: assertDispatched. Но не удалось при последнем утверждении с ошибками ниже: -

The expected [App\Notifications\CustomerCreatedNotification] notification was not sent

1 Ответ

1 голос
/ 03 апреля 2020

Поддельное событие перезаписывает обычные логи событий c и поэтому не будет вызывать слушателей. Это полезно, так как вам иногда нужно блокировать цепочки событий от запуска. Фальсификация - это также не забота о побочных эффектах, потому что их часто очень сложно протестировать.

Но тогда как вы проверяете работоспособность своего кода, я предпочитаю разделить тестирование на побочные эффекты событий в модульном тестировании. Тот же подход с заданиями, так как побочные эффекты труднее утверждать, а тесты становятся достаточно большими, чтобы включать все.

Удалите уведомление об утверждении из исходного теста. Создайте новый в tests/Unit/TestCustomerCreatedEven т или аналогичном.

public function customer_event_listener_tests() {
    // create your data
    $customers = Customer::all();
    $customer = $customers->first();
    $manager = $customer->manager;

    // fake notification only
    Notification::fake();

    $event = new CustomerCreated($customer);
    event($event);

    Notification::assertSentTo(
        $manager,
        CustomerCreatedNotification::class,
        function ($notification, $channels) use ($customer) {
            return $notification->customer->id === $customer->id;
        }
    );
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...