I had a method, that opened a socket connection, used, and then closed it. In order to make it testable, I moved the dealing with the connection to separate methods (see the code below).
Now I want to write a unit test for the barIntrefaceMethod()
and need to mock the method openConnection()
. With other words, I need a fake resource
.
Is it possible / How to "manually" create a variable of the type resource
in PHP (in order to fake handles like "opened files, database connections, image canvas areas and the like" etc.)?
FooClass
class FooClass
{
public function barIntrefaceMethod()
{
$connection = $this->openConnection();
fwrite($connection, 'some data');
$response = '';
while (!feof($connection)) {
$response .= fgets($connection, 128);
}
return $response;
$this->closeConnection($connection);
}
protected function openConnection()
{
$errno = 0;
$errstr = null;
$connection = fsockopen($this->host, $this->port, $errno, $errstr);
if (!$connection) {
// TODO Use a specific exception!
throw new Exception('Connection failed!' . ' ' . $errno . ' ' . $errstr);
}
return $connection;
}
protected function closeConnection(resource $handle)
{
return fclose($handle);
}
}
$resource->openConnection()
. You should consider instead to have a wrapper object around those methods, so that you can test$resource->write('something')
instead offwrite($resource, 'something')
. – TheomorphicbarIntrefaceMethod()
, that calls these wrapping functions. The problem is only, that I don't find any way to fake theresource
. That frustrates mocking of theopenConnection()
. – Nananne