ReflectionException: Class mailer does not exist 反射异常:类 mailer 不存在
ReflectionException: Class mailer does not exist 反射异常:类 mailer 不存在
如果我在测试类中使用\mail
,Laravel 5.7会告诉我类mailer
不存在。
这是我的测试函数:
/** * A basic test example. * * @return void */ public function testBasicTest() { \Mail::raw('Hello world', function($message){ $message->to('foo@bar.com'); $message->from('bar@foo.com'); }); }
当我在终端输入phpunit
时发生这种情况:
1) Tests\Feature\ExampleTest::testBasicTest ReflectionException: Class
mailer does not exist
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Container/Container.php:779
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Container/Container.php:658
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Container/Container.php:609
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:735
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Container/Container.php:1222
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:175
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:144
/home/www/testmachine/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:231
/home/www/testmachine/tests/Feature/ExampleTest.php:14
然而,当我在应用程序的其他地方使用mail时,它可以正常工作,例如在Route.php
中:
Route::get('/test', function(){ \Mail::raw('Hello world', function($message){ $message->to('foo@bar.com'); $message->from('bar@foo.com'); }); dd('hi'); });
我检查了app.php
中的Illuminate\Mail\MailServiceProvider::class
,如这里所建议的,并且我还执行了composer update
,然后执行了composer dump-autoload
,如这里所建议的。
有任何想法为什么会出现这个错误吗?
出现ReflectionException: Class mailer does not exist的原因是测试类中没有正确指定Mail类的命名空间。解决方法是在测试类中使用use语句指定Mail类的命名空间。
具体解决方法如下:
在测试类的开头添加以下代码:
use Illuminate\Support\Facades\Mail;
另外,在进行测试之前,可以先了解一下Laravel的邮件伪造功能(Mail::fake())。详情请参考文档:https://laravel.com/docs/5.7/mocking#mail-fake
另外,还有一种尝试是使用use Illuminate\Support\Facades\Mail;
语句,并使用Mail::
而不是\Mail
,但是仍然出现相同的错误消息。感谢提到faker类。