按照 Lumen 文件,在 unit test 中建立 HTTP request 要呼叫 $this->call(),但沒辦法自訂 header 內容。
細看實作 Laravel\Lumen\Testing\Concerns\MakesHttpRequests::call()
:
/** * Call the given URI and return the Response. * * @param string $method * @param string $uri * @param array $parameters * @param array $cookies * @param array $files * @param array $server * @param string $content * @return \Illuminate\Http\Response */ public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null) { $this->currentUri = $this->prepareUrlForRequest($uri); $symfonyRequest = SymfonyRequest::create( $this->currentUri, $method, $parameters, $cookies, $files, $server, $content ); $this->app['request'] = LumenRequest::createFromBase($symfonyRequest); return $this->response = TestResponse::fromBaseResponse( $this->app->prepareResponse($this->app->handle($this->app['request'])) ); }
從 function parameter 和 return,大概就知道使用這個方法沒辦法塞 header 值。
但是若透過 SymfonyRequest
的話,則可以設定 header 內容:
$request = SymfonyRequest::create(); $request->headers->set('acccess_token', 'ooxx');
因此,若需要自訂 header,則必須 override 原本的 call()
方法。以下是自己改寫的 trait:
use Illuminate\Testing\TestResponse; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; trait ApiTokenRequestTrait { public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null, $headers = []) { $symfonyRequest = SymfonyRequest::create( $uri, $method, $parameters, $cookies, $files, $server, $content ); foreach ($headers as $key => $value) { $symfonyRequest->headers->set($key, $value); } $this->app['request'] = \Laravel\Lumen\Http\Request::createFromBase($symfonyRequest); return TestResponse::fromBaseResponse( $this->app->prepareResponse($this->app->handle($this->app['request'])) ); } }