ApiVersionTest.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace think\tests;
  3. use Mockery as m;
  4. use PHPUnit\Framework\TestCase;
  5. use think\Request;
  6. use think\Route;
  7. class ApiVersionTest extends TestCase
  8. {
  9. use InteractsWithApp;
  10. /** @var Route */
  11. protected $route;
  12. protected function setUp(): void
  13. {
  14. $this->prepareApp();
  15. $this->route = new Route($this->app);
  16. }
  17. protected function tearDown(): void
  18. {
  19. m::close();
  20. }
  21. protected function makeRequest($path, $method = 'GET', $version = null)
  22. {
  23. $request = m::mock(Request::class)->makePartial();
  24. $request->shouldReceive('host')->andReturn('localhost');
  25. $request->shouldReceive('pathinfo')->andReturn($path);
  26. $request->shouldReceive('url')->andReturn('/' . $path);
  27. $request->shouldReceive('method')->andReturn(strtoupper($method));
  28. // 修改header方法的mock
  29. if ($version !== null) {
  30. $request->shouldReceive('header')->andReturnUsing(function($name) use ($version) {
  31. return $name === 'Api-Version' ? $version : null;
  32. });
  33. }
  34. return $request;
  35. }
  36. public function testApiVersionFromHeader()
  37. {
  38. $this->route->group('api', function () {
  39. $this->route->get('products', function () {
  40. return 'v1 products';
  41. })->version('1.0');
  42. $this->route->get('products', function () {
  43. return 'v2 products';
  44. })->version('2.0');
  45. });
  46. // 测试请求头版本1.0
  47. $request = $this->makeRequest('api/products', 'GET', '1.0');
  48. // 添加调试信息
  49. try {
  50. $response = $this->route->dispatch($request);
  51. $this->assertEquals('v1 products', $response->getContent());
  52. } catch (\think\exception\RouteNotFoundException $e) {
  53. var_dump($request->header('Api-Version')); // 检查版本号是否正确传入
  54. throw $e;
  55. }
  56. // 测试请求头版本2.0
  57. $request = $this->makeRequest('api/products', 'GET', '2.0');
  58. $response = $this->route->dispatch($request);
  59. $this->assertEquals('v2 products', $response->getContent());
  60. }
  61. }