I’m trying to test some of my php code but fail with mocking objects. I want to mock a function which does a curl request since it shouldn’t do the request every time/test. Mocking the curl function itself, works. Requiring it for another class and mocking it there, fails.
Here are the files:
helper.curl.php:
class Helper_Curl {
/*
** __construct($callDomain) - construct new curl helper using set calldomain
*/
public function __construct($callDomain) {
$this->callDomain = $callDomain;
}
/*
** sendPostArrayToApi($Array) - HTTP POST request to server
*/
public function sendPostArrayToApi($Array) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->callDomain);
// [... curl Settings ...]
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
}
class.request.php
require_once('helper.curl.php');
class RequestClass {
function _set($data, $set_type='edit'){
// [... some code ...]
$curl = new Helper_Curl('http://example.com');
$xml = $curl->sendPostArrayToApi($InfoArray);
if($xml == "") {
return false;
}
// [... some more code ...]
}
}
And finally the test:
class ClassRequestTest extends PHPUnit_Framework_TestCase {
public function setUp() {
require_once('class.request.php');
}
public function testSetRefund() {
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<response>
<info-id>12345</info-id>
<transmit-id>315</transmit-id>
</response>';
$stubCurl = $this->getMock('Helper_Curl');
$stubCurl->expects($this->once())
->method('sendPostArrayToApi')
->will($this->returnValue($xml));
$this->object->_set($DataArray);
}
protected function tearDown() {
unset($this->object);
}
}
The sendPostArrayToApi function from the class Helper_Curl should be mocked and return the given xml data for the _set function to go on with. How do I attach $stubCurl to $this->object? Is it possible anyhow?
Thanks for your time.
As I understand it you need to use mocking like this in conjunction with auto-loading. Since you have a “hard” dependency on your cURL helper (i.e. a “require_once” in your class.request file) when it gets to that call in the code PHP will only see the real cURL class and will use that. If you use auto-loading, then PHP can intercept the call to autoload that class and substitute the mock.
Otherwise (and this may be a better solution), you should look at some kind of IoC solution whereby the dependency on the cURL class is not hard-coded in your request class (i.e. you don’t instantiate the cURL object directly in the request class). There are various ways to achieve this. DI or perhaps more specifically Dependency Injection Containers are the current trend in PHP. You might also want to look at a Service Locator instead. There’s a good article by Martin Fowler which describes all these patterns and the various pros and cons. With either of these patterns, you can much more easily substitute test objects (mocks or stubs etc) into the code under test.