Skip to content

Instantly share code, notes, and snippets.

@magickatt
Last active December 29, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magickatt/7608776 to your computer and use it in GitHub Desktop.
Save magickatt/7608776 to your computer and use it in GitHub Desktop.
Mocking an API for unit testing in Zend Framework 2
<?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