I am writing some unit tests to test a database transaction middleware, on an exception everything within the transaction should do a rollback. And This piece of code works perfectly fine and passes the unit test:
Unit test method that succeeds
public function testTransactionShouldRollback()
{
Event::fake();
// Ignore the exception so the test itself can continue.
$this->expectException('Exception');
$this->middleware->handle($this->request, function () {
throw new Exception('Transaction should fail');
});
Event::assertDispatched(TransactionRolledBack::class);
}
Yet whenever I test a TransactionBeginning
event it fails to assert the event has been dispatched.
Unit test method that fails
public function testTransactionShouldBegin()
{
Event::fake();
$this->middleware->handle($this->request, function () {
return $this->response;
});
Event::assertDispatched(TransactionBeginning::class);
}
The actual middleware
public function handle($request, Closure $next)
{
DB::beginTransaction();
try {
$response = $next($request);
if ($response->exception) {
throw $response->exception;
}
} catch (Throwable $e) {
DB::rollBack();
throw $e;
}
if (!$response->exception) {
DB::commit();
}
return $response;
}
All transaction events fire off events so DB::beginTransaction, DB::rollBack, DB::commit
should all fire events. Yet When I am testing I only even see the transaction rollback event firing.
Is there a reason why the other events are not firing in this case and my assertDispatched is failing?