Search code examples
laravellaravel-7phpunit

The expected [App\Mail\WelcomeEmail] mailable was not sent. Failed asserting that false is true


Where am i making a mistake ? The blow code does not work for testing. The user is found. There is not a problem like user null.

The error message is:

The expected [App\Mail\WelcomeEmail] mailable was not sent. Failed asserting that false is true.

   at vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php:64
  60|         }
  61| 
  62|         PHPUnit::assertTrue(
  63|             $this->sent($mailable, $callback)->count() > 0,
> 64|             $message
  65|         );
  66|     }
  67| 

Test class

class MailTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testWelcomeMail()
    {
        $this->withoutExceptionHandling();
        Mail::fake();

        Mail::assertSent(WelcomeEmail::class);
    }
}

Mail class

class WelcomeEmail extends Mailable
{
 use Queueable, SerializesModels;

 public $data;

 public function __construct($data)
 {
    $this->data = $data;
 }

 public function build()
 {
    $user = User::find(3425);

    $address = 'myjourney@asdasd.com';
    $subject = __('email.welcome_to_journey');
    $name = __('email.my_journey');

    if ($user != NULL) {
        \App::setLocale($user->lang);
        $user->is_welcome_email_sent = 1;
        $user->save();

    }

    return $this->view('email.user_welcome', ['user' => $user])
        ->from($address, $name)
        // ->cc($address, $name)
        // ->bcc($address, $name)
        ->replyTo($address, $name)
        ->subject($subject);
 }
}

I can work other testing files like login, register etc but mailing didnt.


Solution

  • You are not sending the email along with the other credentials. Your function should look like that

    public function testWelcomeMail()
    {
        $this->withoutExceptionHandling();
        Mail::fake();
        Mail::to('<email_address>')->send(new WelcomeEmail(['user' => <some_number>]));
        Mail::assertSent(WelcomeEmail::class);
    }