public
Last active

Mock-testing web services in Zend Framework

  • Download Gist
mock-testing-webservices.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
public function testGetTracks()
{
// Create mocks for the SoundCloud class for testing purposes
$webservice = $this->getMockBuilder('\Soundcloud\Services\Soundcloud')
->setConstructorArgs(array(
$this->config->soundcloud->clientId,
$this->config->soundcloud->clientSecret))
->setMethods(array('get', 'setAccessToken'))
->getMock();
$myInfo = file_get_contents(FIXTURE_PATH . '/soundcloud_my_info.txt');
$playlists = file_get_contents(FIXTURE_PATH . '/soundcloud_playlists.txt');
$tracks = file_get_contents(FIXTURE_PATH . '/soundcloud_tracks.txt');
$inputs = array('me', 'playlists', 'tracks');
$outputs = array($myInfo, $playlists, $tracks);
$expectation = $webservice->expects($this->exactly(3))->method('get');
$this->setMultipleMatching($expectation, $inputs, $outputs);
$this->soundcloud = new \Soundcloud\Client(
$webservice,
$this->config->soundcloud->clientId,
$this->config->soundcloud->clientSecret
);
$this->soundcloud->setAccessToken(
'<user>',
'<password>',
$this->config->soundcloud->tokenUrl
);
$myInfo = $this->soundcloud->getMyInfo();
$mySoundcloudId = $myInfo['id'];
 
$playlists = $this->soundcloud->getPlaylists($this->config->soundcloud->consumer_key);
$this->assertTrue(count($playlists) > 0, 'Found one or more SoundCloud playlists');
 
$tracks = $this->soundcloud->getAllTracks($mySoundcloudId);
$this->assertTrue(count($tracks) > 0, 'Found one or more tracks from SoundCloud');
}
 
public function setMultipleMatching($expectation, array $inputs, array $outputs)
{
$testCase = $this;
$callback = function() use ($inputs, $outputs, $testCase) {
$args = func_get_args();
$testCase->assertContains($args[0], $inputs);
$index = array_search($args[0], $inputs);
return $outputs[$index];
};
$expectation->will($this->returnCallback($callback));
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.