Laravel 5.3.8 is released with new fakes for events, jobs, mail, and notifications
Published on by Eric L. Barnes
Laravel 5.3.8 is now released with new improvements for testing by included new fakes for events, jobs, mail, and notifications.
Here is a quick look at how these new testing featurs work:
Laravel Events
Laravel now provides three helpers for mocking events. The first is expectsEvents
method which verifies the expected events are fired, but prevents any listeners for those events from executing. The second is the inverse doesntExpectEvents
to verify that the given events are not fired:
public function testOrderShipping(){ $this->expectsEvents(OrderShipped::class); $this->doesntExpectEvents(OrderFailedToShip::class);
The next helper is withoutEvents
which prevents all events from running:
public function testUserRegistration(){ $this->withoutEvents();
As an alternative to mocking, you may use the Event facade’s fake method to prevent all event listeners from executing.
use App\Events\OrderShipped;use App\Events\OrderFailedToShip;use Illuminate\Support\Facades\Event; class ExampleTest extends TestCase{ /** * Test order shipping. */ public function testOrderShipping() { Event::fake(); // Perform order shipping... Event::assertFired(OrderShipped::class, function ($e) use ($order) { return $e->order->id === $order->id; }); Event::assertNotFired(OrderFailedToShip::class); }}
These same style helpers can also be used in jobs, mail, and notifications and the documentation is already updated with all the details.
Upgrading to 5.3.8 should just be a matter of running composer update
and these new features will be available to be used.
Eric is the creator of Laravel News and has been covering Laravel since 2012.