DispatcherTest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace think\http\tests\middleware;
  3. use PHPUnit\Framework\TestCase;
  4. use think\http\middleware\Dispatcher;
  5. use think\http\middleware\MissingResponseException;
  6. use think\Request;
  7. use think\Response;
  8. class DispatcherTest extends TestCase
  9. {
  10. public function testValidMiddleware()
  11. {
  12. $dispatcher = new Dispatcher();
  13. $dispatcher->add(function () {
  14. });
  15. $this->assertCount(1, $dispatcher->all());
  16. $this->expectException(\InvalidArgumentException::class);
  17. $dispatcher->add('foo middleware');
  18. }
  19. public function testAddAndInsert()
  20. {
  21. $middleware1 = function () {};
  22. $middleware2 = function () {};
  23. $dispatcher = new Dispatcher();
  24. $dispatcher->add($middleware1);
  25. $dispatcher->insert($middleware2);
  26. $this->assertSame([$middleware2, $middleware1], $dispatcher->all());
  27. }
  28. public function testDispatch()
  29. {
  30. $middleware1 = function ($request, $next) {
  31. return $next($request);
  32. };
  33. $middleware2 = function ($request) {
  34. return Response::create('hello world');
  35. };
  36. $dispatcher = new Dispatcher([$middleware1, $middleware2]);
  37. $response = $dispatcher->dispatch(new Request());
  38. $this->assertInstanceOf(Response::class, $response);
  39. $this->assertEquals('hello world', $response->getContent());
  40. }
  41. public function testDispatchWithoutResponse()
  42. {
  43. $middleware1 = function ($request, $next) {
  44. return $next($request);
  45. };
  46. $middleware2 = function ($request, $next) {
  47. return $next($request);
  48. };
  49. $dispatcher = new Dispatcher([$middleware1, $middleware2]);
  50. $this->expectException(MissingResponseException::class);
  51. $dispatcher->dispatch(new Request());
  52. }
  53. public function testDispatchWithBadResponse()
  54. {
  55. $middleware = function ($request, $next) {
  56. return 'invalid response';
  57. };
  58. $dispatcher = new Dispatcher($middleware);
  59. $this->expectException(\LogicException::class);
  60. $dispatcher->dispatch(new Request());
  61. }
  62. }