Last active
December 29, 2015 03:39
-
-
Save magickatt/7608776 to your computer and use it in GitHub Desktop.
Mocking an API for unit testing in Zend Framework 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Mock JSON | |
$json = <<< JSON | |
{ | |
"timestamp": 1385150462, | |
"stuff": { | |
"this": 2, | |
"that": 4, | |
"other": 1 | |
} | |
} | |
JSON | |
// Mock the client so it always returns the JSON we want | |
$mockResponse = $this->getMock('\Zend\Http\Response'); | |
$mockResponse->expects($this->any()) | |
->method('getContent') | |
->will($this->returnValue($json)); | |
// Mock the client so that it always returns the pre-prepared response | |
$mockClient = $this->getMock('\Zend\Http\Client'); | |
$mockClient->expects($this->any()) | |
->method('send') | |
->will($this->returnValue($mockResponse)); | |
$object->setClient($mockClient); | |
/* | |
* Inside your concrete object | |
*/ | |
// The client injected into your object would be the mock client created in the test | |
$client = $mockClient; | |
// The response will be the mock response created in the test | |
$client->setUri('http://wherever.com'); | |
$response = $mockClient->send(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment