+1
I'd like to get some pointers as well.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey guys,
I feel the title says it all, but regardless... I'm trying to figure out the best way to go about testing Event Listeners.
Using events has made integration testing a breeze since I can focus on only testing the actions that take place in the, well, controller action. However, I still want to ensure that I have complete test coverage against all aspects of my codebase, especially since several of these listeners are responsible for triggering billing systems and such.
My guess is likely just writing standard unit tests in PHPUnit, though I feel like this may look somewhat awkward as PHPUnit is also running my integration tests using the new syntax that was brought in from the Laracast "Integrated" package.
Thoughts?
Here's an example of how I'm testing an event listener that sets a user's last sign in and active dates and IP address.
<?php
use App\Events\Users\SignedIn;
use App\Listeners\Users\SignedInListener;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
class UsersSignedInListenerTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->carbon = Mockery::mock(Carbon::class);
$this->request = Mockery::mock(Request::class);
$this->user = Mockery::mock(User::class)->makePartial();
}
/**
* Test event listener set users last signin and active timestamps and
* IP address.
*/
public function testHandle()
{
$time = time();
$ip = '127.0.0.1';
$this->carbon->shouldReceive('now')->once()->andReturn($time);
$this->request->shouldReceive('ip')->once()->andReturn($ip);
$this->user->shouldReceive('save')->once()->andReturn(true);
$listener = new SignedInListener($this->carbon, $this->request);
$listener->handle(new SignedIn($this->user));
$this->assertSame($time, $this->user->last_signin_at);
$this->assertSame($time, $this->user->last_active_at);
$this->assertSame($ip, $this->user->ip);
}
}
Please or to participate in this conversation.