diff --git a/phpunit.xml b/phpunit.xml index eb0d050..1af24d5 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,10 +1,5 @@ - - - - - - + tests @@ -17,7 +12,7 @@ - src/ + src/ diff --git a/src/InteractsWithServiceProvider.php b/src/InteractsWithServiceProvider.php index c1ffb69..520542c 100644 --- a/src/InteractsWithServiceProvider.php +++ b/src/InteractsWithServiceProvider.php @@ -91,6 +91,25 @@ protected function assertHasShared(string ...$services): void $this->assertHasSingletons(...$services); } + /** + * Assert an event has registered certain listeners. + * + * @param class-string $event + * @param class-string ...$listeners + */ + protected function assertHasListeners(string $event, string ...$listeners): void + { + $list = $this->app->make('events')->getRawListeners(); + + static::assertNotEmpty($list[$event] ?? null, "The is no listeners registered for the [$event] event."); + + foreach ($listeners as $listener) { + static::assertContains( + $listener, $list[$event], "The [$listener] listener was not registered for [$event] event.", + ); + } + } + /** * Assert that the config file is merged into the application using the given key. */ diff --git a/tests/InteractsWithServiceProviderTest.php b/tests/InteractsWithServiceProviderTest.php index 9e8712d..bee1088 100644 --- a/tests/InteractsWithServiceProviderTest.php +++ b/tests/InteractsWithServiceProviderTest.php @@ -3,6 +3,7 @@ namespace Tests; use Closure; +use Illuminate\Auth\Events\Login; use Illuminate\Auth\SessionGuard; use Illuminate\Console\Command; use Illuminate\Console\Scheduling\Schedule; @@ -150,6 +151,39 @@ public function test_assert_singletons_fails_if_not_registered(): void $this->assertHasSingletons('foo'); } + public function test_assert_has_listeners(): void + { + $this->app->make('events')->listen('foo', 'foo-listener'); + + $this->assertHasListeners('foo'); + $this->assertHasListeners('foo', 'foo-listener'); + } + + public function test_assert_has_listeners_with_closure(): void + { + $this->app->make('events')->listen(fn (Login $event) => true); + + $this->assertHasListeners(Login::class); + } + + public function test_assert_has_listeners_errors_with_no_listeners(): void + { + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The is no listeners registered for the [Illuminate\Auth\Events\Login] event.'); + + $this->assertHasListeners(Login::class); + } + + public function test_assert_has_listeners_errors_with_listener_not_listed(): void + { + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The [invalid] listener was not registered for [Illuminate\Auth\Events\Login] event.'); + + $this->app->make('events')->listen(Login::class, 'foo-listener'); + + $this->assertHasListeners(Login::class, 'invalid'); + } + public function test_assert_merged_config(): void { File::expects('getRequire')->with('foo/bar.php')->andReturn(['foo' => 'bar']);