Ich baute einen Service für meine Laravel 5.1 API, die YouTube sucht. Ich versuche, einen Test dafür zu schreiben, habe aber Probleme herauszufinden, wie man die Funktionalität verspotten kann. Unten ist der Service.Müssen einen Dienst testen, der CURL in Laravel verwendet 5.1
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];
}
}
Ich habe diesen Dienst erstellt, um die Funktionalität von einem Controller zu abstrahieren. Ich benutzte dann Mockery, um den Controller zu testen. Jetzt muss ich herausfinden, wie man den oben genannten Dienst testet. Jede Hilfe wird geschätzt.
Vielen Dank! – WebDev84