title: Stubbing a method called by a class' constructor
body: <p>How does one stub a method in PHPUnit that is called by the class under test's constructor? The simple code below for example won't work because by the time I declare the stubbed method, the stub object has already been created and my method called, unstubbed.</p>
  
  <p>Class to test:</p>
  
  <pre><code>class ClassA {
    private $dog;
    private $formatted;
  
    public function __construct($param1) { 
       $this-&gt;dog = $param1;       
       $this-&gt;getResultFromRemoteServer();
    }
  
    // Would normally be private, made public for stubbing
    public getResultFromRemoteServer() {
      $this-&gt;formatted = file_get_contents('http://whatever.com/index.php?'.$this-&gt;dog);
    }
  
    public getFormatted() {
      return ("The dog is a ".$this-&gt;formatted);
    }
  }
  </code></pre>
  
  <p>Test code:</p>
  
  <pre><code>class ClassATest extends PHPUnit_Framework_TestCase {
    public function testPoodle() {  
      $stub = $this-&gt;getMockBuilder('ClassA')
                   -&gt;setMethods(array('getResultFromRemoteServer'))
                   -&gt;setConstructorArgs(array('dog52'))
                   -&gt;getMock();
  
      $stub-&gt;expects($this-&gt;any())
           -&gt;method('getResultFromRemoteServer')
           -&gt;will($this-&gt;returnValue('Poodle'));
  
      $expected = 'This dog is a Poodle';
      $actual = $stub-&gt;getFormatted();
      $this-&gt;assertEquals($expected, $actual);
    }
  }
  </code></pre>