2

I am trying to test emails in laravel 5 and I have realised that Swift_Mailer triggers Illuminate\Mail\Events\MessageSending event whenever a mail is being sent.

But since I am beginner, I am having trouble comprehending how to listen to this event and take out the underlying message object?

I have tried this but I don't this is correct:

public function test_the_email_via_listening_to_message_sending_event()
{
    $user = factory(User::class)->create();
    Event::fire(new UserWasCreated($user));

    Event::listen(Illuminate\Mail\Events\MessageSending::class, function($message){
        echo 'Hello';
    });
}

How to listen to a particular event in a test case and trigger code in response to it?

Rohan
  • 13,308
  • 21
  • 81
  • 154

1 Answers1

0

Laravel provides an expectsEvents method: https://laravel.com/docs/5.2/testing#mocking-events

$this->expectsEvents(Illuminate\Mail\Events\MessageSending::class);
Angad Dubey
  • 5,067
  • 7
  • 30
  • 51
  • I am not trying to mock events. In fact I am trying to do high level functional testing where I am trying to catch the emails before they are sent and assert that the subject, body and so on are in a certain way. Which is why I am looking for a way to trap the email before it is sent and perform assertions on it. – Rohan Apr 05 '16 at 07:38
  • @Rohan In that case, you might do best checking Laravel's own tests for the Mail functionality. https://github.com/laravel/framework/blob/5.2/tests/Mail/MailMessageTest.php – ceejayoz Apr 05 '16 at 11:46