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

Viewed 1688

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.

2 Answers

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);
}

Is there actually a User with id 3425?

$user = User::find(3425);

Your code might break here, since we cannot retrieve lang from a null object. This line should probably be removed as it already is used on a line further below where you check if the user exists.

\App::setLocale($user->lang); 

It also seems like your email template uses data from the $user, since the user object is passed to the template. This may also break if you expect the user to exist.

Related