MailThief is a new extension package written by Tighten Co. It is used to simulate mail sending in the Laravel application. With this extension package, we can test mail sending without sending emails, this may be a bit difficult to say. Here we will explain it through a specific instance.
Assume that we have registered such a route before successfully sending a welcome email to the new user:
Route: post ('register ', function (){
// <Snip> Here is the registration implementation logic </snip>
Mail: send ('emails. welcome ', [], function ($ m ){
$ Email = request ('email ');
$ M-> to ($ email ),
$ M-> subject ('Welcome to my app! ');
$ M-> from ('noreply @ example.com ');
$ M-> bcc ('notifications @ example.com ');
});
// <Snip> response </snip>
});
This function is usually very difficult to test. We need to manually register it. If the sending fails, we have to re-register the process, but with MailThief, everything will become simple:
First, we need to install the extension through Composer:
Composer require tightenco/mailthief
Next we will use the following Artisan command to create a test class:
Php artisan make: test RegistrationTest
Then modify the test method as follows:
Use MailThief \ Facades \ MailThief;
Class RegistrationTest extends TestCase {
Public function testNewUserRegistered ()
{
// This step is very important to block and intercept outgoing mails!
MailThief: hijack ();
$ This-> post ('register ',[
'Name' => 'John Doe ',
'Email '=> 'John @ example.com ',
'Password' => 'secret ',
]);
// Check whether the email has been sent to the specified email address
$ This-> assertTrue (MailThief: hasMessageFor ('John @ example.com '));
// You can also include a cc email address.
$ This-> assertTrue (MailThief: hasMessageFor ('notifications @ example.com '));
// Ensure that the email subject is correct
$ This-> assertEquals ('welcome to Laravel college! ', MailThief: lastMessage ()-> subject );
// Make sure the email comes from the correct sending address
// ('From' can be a list, so we return it as a set)
$ This-> assertEquals ('noreply @ example.com ', MailThief: lastMessage ()-> from-> first ());
}
}
Then, run the phpunit command on the command line to test the user registration and email sending function.