Laravel Testing Issue: Mocking Event Facade
Published in
1 min readAug 9, 2019
Laravel provides helpers for mocking events, jobs, and facades out of the box. These helpers primarily provide a convenience layer over Mockery so you do not have to manually make complicated Mockery method calls.
Today first time I used Event::fake() and faced really weird issue when I run tests.
public function testPostCreating()
{
Event::fake(); $response = $this->json('POST', '/api/v1/posts', [
'title' => 'Example Post',
]); Event::assertDispatched(PostCreated::class);
}
Event
facade's fake
method prevents all event listeners from executing. And because of we're generating UUID from our model events I got exception below:
[2019-08-09 14:30:22] testing.ERROR: SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "id" violates not-null constraint
I found quick, dirty workaround to fix:
public function testPostCreating()
{
$initialDispatcher = Event::getFacadeRoot();
Event::fake();
Model::setEventDispatcher($initialDispatcher); $response = $this->json('POST', '/api/v1/posts', [
'title' => 'Example Post',
]); Event::assertDispatched(PostCreated::class);
}