I have a following method, which retrieves top visited pages from Google Analytics:
public function getData($limit = 10)
{
$ids = '12345';
$dateFrom = '2011-01-01';
$dateTo = date('Y-m-d');
// Google Analytics credentials
$mail = 'my_mail';
$pass = 'my_pass';
$clientLogin = Zend_Gdata_ClientLogin::getHttpClient($mail, $pass, "analytics");
$client = new Zend_Gdata($clientLogin);
$reportURL = 'https://www.google.com/analytics/feeds/data?';
$params = array(
'ids' => 'ga:' . $ids,
'dimensions' => 'ga:pagePath,ga:pageTitle',
'metrics' => 'ga:visitors',
'sort' => '-ga:visitors',
'start-date' => $dateFrom,
'end-date' => $dateTo,
'max-results' => $limit
);
$query = http_build_query($params, '');
$reportURL .= $query;
$results = $client->getFeed($reportURL);
$xml = $results->getXML();
Zend_Feed::lookupNamespace('default');
$feed = new Zend_Feed_Atom(null, $xml);
$top = array();
foreach ($feed as $entry) {
$page['visitors'] = (int) $entry->metric->getDOM()->getAttribute('value');
$page['url'] = $entry->dimension[0]->getDOM()->getAttribute('value');
$page['title'] = $entry->dimension[1]->getDOM()->getAttribute('value');
$top[] = $page;
}
return $top;
}
It needs some refactoring for sure, but the question is:
- How would you write PHPUnit tests for this method?
David Weinraub gave you the first half (how to set up your class to be mockable), so I’ll address the second half (how to build the mock).
PHPUnit provides a great mocking facility with a simple API. Passing the user and password is too simple to test in my book, so I’d mock just the handling of the query and results. This requires mocks for Zend_Gdata and Zend_Gdata_App_Feed.
The above will test that the URL was correct and return the XML feed expected from Google. It removes all dependence on the Zend_Gdata classes. If you don’t use type hinting on setClient(), you can even use stdClass as the base for the two mocks since you will only be using mocked methods.