Skip to content

Instantly share code, notes, and snippets.

@lboynton
Created September 18, 2012 18:34
Show Gist options
  • Save lboynton/3744912 to your computer and use it in GitHub Desktop.
Save lboynton/3744912 to your computer and use it in GitHub Desktop.
Unit Testing Zend_Http_Client Based Web Service Calls
<?php
namespace App\Service;
/**
* Some web service client
*
* @author Lee Boynton
*/
class WebService
{
/**
* @var \Zend_Http_Client
*/
private $client = false;
/**
* @var string
*/
private $uri;
/**
* @param string $uri Web service API endpoint (single endpoint, this is an
* RPC style web service)
*/
public function __construct($uri)
{
$this->uri = $uri;
}
/**
* @return \Zend_Http_Client
*/
public function getHttpClient()
{
if (!$this->client)
{
$this->client = $this->getDefaultHttpClient();
}
$this->client->setUri($this->uri);
return $this->client;
}
/**
* @param \Zend_Http_Client $client
*/
public function setHttpClient(\Zend_Http_Client $client)
{
$this->client = $client;
}
private function getDefaultHttpClient()
{
return new \Zend_Http_Client();
}
/**
* Call web service
* @return string Just return the body of the request
* @throws \RuntimeException If request fails
*/
public function callWebService()
{
$client = $this->getHttpClient();
$client->setParameterGet('test', 'test');
try
{
$response = $client->request();
}
catch(\Zend_Http_Client_Adapter_Exception $exception)
{
throw new \RuntimeException('Request failed', null, $exception);
}
return $response->getBody();
}
}
<?php
namespace AppTest\Service;
use App\Service\WebService;
/**
* Test class for App_Service_WebService
*
* @author Lee Boynton
*/
class WebServiceTest extends \PHPUnit_Framework_TestCase
{
/**
* @var App\Service\WebService
*/
protected $webService;
/**
* @var \Zend_Http_Client_Adapter_Interface
*/
protected $adapter;
public function setUp()
{
$this->webService = new WebService('http://fake');
$this->adapter = new \Zend_Http_Client_Adapter_Test();
$this->webService->getHttpClient()->setAdapter($this->adapter);
}
public function testCallWebServiceWhenSuccessful()
{
// web service call will return "ok"
$this->adapter->setResponse(
"HTTP/1.1 200 OK" . "\r\n" .
"Content-Type: text/html" . "\r\n" .
"\r\n" .
'ok');
$this->assertEquals('ok', $this->webService->callWebService());
}
public function testCallWebServiceWhenUnsuccessful()
{
$this->setExpectedException('RuntimeException');
$this->adapter->setNextRequestWillFail(true);
$this->webService->callWebService();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment