我对测试很新,所以希望能得到帮助。首先,这是我的代码,位于App目录下(Laravel 5.5)。
// controller
public function store(Request $request)
{
$foo = new Foo($request->only([
'email',
'value 2',
'value 3',
]));
$foo->save();
event(new FooCreated($foo));
return redirect()->route('/');
}
// Events/FooCreated
use App\Foo;
class FooCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $foo;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
}
// Listeners/
use App\Events\FooCreated;
use App\Mail\FooSendingEmail;
class EmailSendListener
{
/**
* Handle the event.
*
* @param EnquiryWasCreated $event
* @return void
*/
public function handle(FooCreated $event)
{
\Mail::to($event->foo->email)->send(new FooSendingEmail($event->foo));
}
}
现在,我正在尝试为触发电子邮件发送的事件和侦听器编写一些测试,因此我在unit/ExampleTest.php中创建了一个方法。
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Foo;
use Illuminate\Support\Facades\Event;
use App\Events\FooCreated;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function testEventTriggered(){
Event::fake();
$foo = factory(\App\Foo::class)->create();
Event::assertDispatched(FooCreated::class, function($event) use ($foo){
return $event->foo->id == $foo->id;
});
}
}
// assume similar this applies for emails according to docs https://laravel.com/docs/5.5/mocking#mail-fake
但是当我运行这个测试时,会出现错误:
The expected [App\Events\FooEvent] event was not dispatched. Failed asserting that false is true.
我该如何修复事件测试才能通过,并且测试发送电子邮件?提前感谢您的帮助。
更新:
我已经成功添加了一个控制器触发事件的测试,但我需要一个测试来检查是否触发了电子邮件。
public function testStore()
{
Event::fake();
$this->post(route('foo.store'), [
'full_name' => 'John Doe',
'email' => 'johndoe@example.com',
'body' => 'Lorem ipsum dolor sit amet',
]);
$foo = Foo::first();
Event::assertDispatched(FooCreated::class, function ($event) use ($foo) {
return $event->foo->id === $foo->id;
});
}
public function testEmailSent()
{
Mail::fake();
// similar to prevous one in order to fire the event
$this->post(route('foo.store'), [
'full_name' => 'John Doe',
'email' => 'johndoe@example.com',
'body' => 'Lorem ipsum dolor sit amet',
'reference_code' => str_random(25),
]);
$foo = Foo::first();
Mail::assertSent(FooSendingEmail::class, function ($mail) use ($foo) {
return $mail->hasTo($foo->email);
});
}
store()
中,而不是在Foo::create()
中,因此基本上我会在数据库中插入新记录,然后触发事件以发送电子邮件。 - ltdev