我爲我的Laravel 5.1 API構建了一項服務,用於搜索YouTube。我正在爲它編寫一個測試,但在解決如何模擬功能時遇到困難。以下是服務。需要測試在Laravel 5.1中使用CURL的服務
class Youtube
{
/**
* Youtube API Key
*
* @var string
*/
protected $apiKey;
/**
* Youtube constructor.
*
* @param $apiKey
*/
public function __construct($apiKey)
{
$this->apiKey = $apiKey;
}
/**
* Perform YouTube video search.
*
* @param $channel
* @param $query
* @return mixed
*/
public function searchYoutube($channel, $query)
{
$url = 'https://www.googleapis.com/youtube/v3/search?order=date' .
'&part=snippet' .
'&channelId=' . urlencode($channel) .
'&type=video' .
'&maxResults=25' .
'&key=' . urlencode($this->apiKey) .
'&q=' . urlencode($query);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
if (is_array($result) && count($result)) {
return $this->extractVideo($result);
}
return $result;
}
/**
* Extract the information we want from the YouTube search resutls.
* @param $params
* @return array
*/
protected function extractVideo($params)
{
/*
// If successful, YouTube search returns a response body with the following structure:
//
//{
// "kind": "youtube#searchListResponse",
// "etag": etag,
// "nextPageToken": string,
// "prevPageToken": string,
// "pageInfo": {
// "totalResults": integer,
// "resultsPerPage": integer
// },
// "items": [
// {
// "kind": "youtube#searchResult",
// "etag": etag,
// "id": {
// "kind": string,
// "videoId": string,
// "channelId": string,
// "playlistId": string
// },
// "snippet": {
// "publishedAt": datetime,
// "channelId": string,
// "title": string,
// "description": string,
// "thumbnails": {
// (key): {
// "url": string,
// "width": unsigned integer,
// "height": unsigned integer
// }
// },
// "channelTitle": string,
// "liveBroadcastContent": string
// }
// ]
//}
*/
$results = [];
$items = $params['items'];
foreach ($items as $item) {
$videoId = $items['id']['videoId'];
$title = $items['snippet']['title'];
$description = $items['snippet']['description'];
$thumbnail = $items['snippet']['thumbnails']['default']['url'];
$results[] = [
'videoId' => $videoId,
'title' => $title,
'description' => $description,
'thumbnail' => $thumbnail
];
}
// Return result from YouTube API
return ['items' => $results];
}
}
我創建了此服務以從控制器中抽象該功能。然後我用Mockery來測試控制器。現在我需要弄清楚如何測試上面的服務。任何幫助表示讚賞。
非常感謝! – WebDev84