title: How to fake a resourse for a unit test in PHP?
body: <p>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).</p>
  
  <p>Now I want to write a unit test for the <code>barIntrefaceMethod()</code> and need to mock the method <code>openConnection()</code>. With other words, I need a fake <code>resource</code>.</p>
  
  <p><strong>Is it possible / How to "manually" create a variable of the type <code>resource</code> in PHP (in order to fake handles like "<a href="http://php.net/manual/en/language.types.resource.php#language.types.resource.casting" rel="noreferrer">opened files, database connections, image canvas areas and the like</a>" etc.)?</strong></p>
  
  <hr>
  
  <p><strong><code>FooClass</code></strong></p>
  
  <pre><code>class FooClass
  {
      public function barIntrefaceMethod()
      {
          $connection = $this-&gt;openConnection();
          fwrite($connection, 'some data');
          $response = '';
          while (!feof($connection)) {
              $response .= fgets($connection, 128);
          }
          return $response;
          $this-&gt;closeConnection($connection);
      }
  
      protected function openConnection()
      {
          $errno = 0;
          $errstr = null;
          $connection = fsockopen($this-&gt;host, $this-&gt;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);
      }
  }
  </code></pre>