Skip to content

Instantly share code, notes, and snippets.

@magickatt
Last active Dec 29, 2015
Embed
What would you like to do?
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