BroadcastedEventsTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace Illuminate\Tests\Events;
  3. use Illuminate\Container\Container;
  4. use Illuminate\Contracts\Broadcasting\Factory as BroadcastFactory;
  5. use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
  6. use Illuminate\Events\Dispatcher;
  7. use Mockery as m;
  8. use PHPUnit\Framework\TestCase;
  9. class BroadcastedEventsTest extends TestCase
  10. {
  11. protected function tearDown(): void
  12. {
  13. m::close();
  14. }
  15. public function testShouldBroadcastSuccess()
  16. {
  17. $d = m::mock(Dispatcher::class);
  18. $d->makePartial()->shouldAllowMockingProtectedMethods();
  19. $event = new BroadcastEvent;
  20. $this->assertTrue($d->shouldBroadcast([$event]));
  21. $event = new AlwaysBroadcastEvent;
  22. $this->assertTrue($d->shouldBroadcast([$event]));
  23. }
  24. public function testShouldBroadcastAsQueuedAndCallNormalListeners()
  25. {
  26. unset($_SERVER['__event.test']);
  27. $d = new Dispatcher($container = m::mock(Container::class));
  28. $broadcast = m::mock(BroadcastFactory::class);
  29. $broadcast->shouldReceive('queue')->once();
  30. $container->shouldReceive('make')->once()->with(BroadcastFactory::class)->andReturn($broadcast);
  31. $d->listen(AlwaysBroadcastEvent::class, function ($payload) {
  32. $_SERVER['__event.test'] = $payload;
  33. });
  34. $d->dispatch($e = new AlwaysBroadcastEvent);
  35. $this->assertSame($e, $_SERVER['__event.test']);
  36. }
  37. public function testShouldBroadcastFail()
  38. {
  39. $d = m::mock(Dispatcher::class);
  40. $d->makePartial()->shouldAllowMockingProtectedMethods();
  41. $event = new BroadcastFalseCondition;
  42. $this->assertFalse($d->shouldBroadcast([$event]));
  43. $event = new ExampleEvent;
  44. $this->assertFalse($d->shouldBroadcast([$event]));
  45. }
  46. }
  47. class BroadcastEvent implements ShouldBroadcast
  48. {
  49. public function broadcastOn()
  50. {
  51. return ['test-channel'];
  52. }
  53. public function broadcastWhen()
  54. {
  55. return true;
  56. }
  57. }
  58. class AlwaysBroadcastEvent implements ShouldBroadcast
  59. {
  60. public function broadcastOn()
  61. {
  62. return ['test-channel'];
  63. }
  64. }
  65. class BroadcastFalseCondition extends BroadcastEvent
  66. {
  67. public function broadcastWhen()
  68. {
  69. return false;
  70. }
  71. }