测试laravel 的控制器层会涉及到Requst对象,故而得构造Request,尝试两种解决方案。
/**
* 封装公共请求方法
* @param $method
* @param $url
* @param $options
*
* @return mixed|\Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function my_http($method, $url, $options) {
//设置请求头
$headers = [
'Accept' => 'application/json',
'Grant-Type' => 'authorization_code'
];
$config['headers'] = $headers;
//请求创建对象
$http = new Client($config);
$response = $http->request($method, "http://xxx/api/{$url}", $options);
return $response;
}
/**
*测试
*/
public function testStats() {
$options['query'] = [
'timeFrame' => 'WEEK',
'createdAt' => '2020-05-01;2020-05-31'
];
$response = $this->my_http('GET', "orders/stats", $options);
$this->assertEquals('200', $response->getStatusCode());
}
public function testStore() {
//数据
$options = [
];
//查看 Request::create底层代码发现 request请求头需要以HTTP_前缀打头。
$headers = [
'HTTP_ACCEPT' => 'application/json',
'HTTP_Grant-Type' => 'authorization_code',
'SERVER_PORT' => 8000,
];
$request = Request::create('/orders', 'POST', $options, [], [], $headers);
$response = $this->controller()->store($request);
$this->assertEquals('200', $response->getStatusCode());
}