EventsSubscriberTest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Illuminate\Tests\Events;
  3. use Illuminate\Container\Container;
  4. use Illuminate\Events\Dispatcher;
  5. use Mockery as m;
  6. use PHPUnit\Framework\TestCase;
  7. class EventsSubscriberTest extends TestCase
  8. {
  9. protected function tearDown(): void
  10. {
  11. m::close();
  12. }
  13. public function testEventSubscribers()
  14. {
  15. $this->expectNotToPerformAssertions();
  16. $d = new Dispatcher($container = m::mock(Container::class));
  17. $subs = m::mock(ExampleSubscriber::class);
  18. $subs->shouldReceive('subscribe')->once()->with($d);
  19. $container->shouldReceive('make')->once()->with(ExampleSubscriber::class)->andReturn($subs);
  20. $d->subscribe(ExampleSubscriber::class);
  21. }
  22. public function testEventSubscribeCanAcceptObject()
  23. {
  24. $this->expectNotToPerformAssertions();
  25. $d = new Dispatcher;
  26. $subs = m::mock(ExampleSubscriber::class);
  27. $subs->shouldReceive('subscribe')->once()->with($d);
  28. $d->subscribe($subs);
  29. }
  30. public function testEventSubscribeCanReturnMappings()
  31. {
  32. $d = new Dispatcher;
  33. $d->subscribe(DeclarativeSubscriber::class);
  34. $d->dispatch('myEvent1');
  35. $this->assertSame('L1_L2_', DeclarativeSubscriber::$string);
  36. $d->dispatch('myEvent2');
  37. $this->assertSame('L1_L2_L3', DeclarativeSubscriber::$string);
  38. }
  39. }
  40. class ExampleSubscriber
  41. {
  42. public function subscribe($e)
  43. {
  44. // There would be no error if a non-array is returned.
  45. return '(O_o)';
  46. }
  47. }
  48. class DeclarativeSubscriber
  49. {
  50. public static $string = '';
  51. public function subscribe()
  52. {
  53. return [
  54. 'myEvent1' => [
  55. self::class.'@listener1',
  56. self::class.'@listener2',
  57. ],
  58. 'myEvent2' => [
  59. self::class.'@listener3',
  60. ],
  61. ];
  62. }
  63. public function listener1()
  64. {
  65. self::$string .= 'L1_';
  66. }
  67. public function listener2()
  68. {
  69. self::$string .= 'L2_';
  70. }
  71. public function listener3()
  72. {
  73. self::$string .= 'L3';
  74. }
  75. }