title: Mocking Email component in CakePHP Call to a member function on a non-object
body: <p>I'm trying to mock an email component in a model, but after the first function, Cake gives me an error: Error: Call to a member function to() on a non-object</p>
  
  <p>Here's my test class:</p>
  
  <pre><code>&lt;?php
  App::uses('User', 'Model');
  
  class UserTest extends CakeTestCase {
  .
  .
  // I'm not copying the setUp and tearDown methods here, but they are there.
  .
  .
      public function testEmailTest(){
          $CakeEmail  = $this-&gt;getMock('CakeEmail',array('to','subject'));
          $CakeEmail-&gt;expects($this-&gt;any())
                  -&gt;method('to')
                  -&gt;with($this-&gt;equalTo('ant@b.com'));
          $CakeEmail-&gt;expects($this-&gt;once())
                  -&gt;method('subject')
                  -&gt;with($this-&gt;equalTo('hi'));
          $this-&gt;User-&gt;CakeEmail = $CakeEmail;
          $result = $this-&gt;User-&gt;emailCat();
      }
  }
  </code></pre>
  
  <p>Here's the User model:
   
  
  <pre><code>public $CakeEmail = null;
  
  public function emailCat() {
      if ( !$this-&gt;CakeEmail){
          $this-&gt;CakeEmail = new CakeEmail();
      }
      $this-&gt;CakeEmail-&gt;subject('hi')
              -&gt;to('ant@b.com')
              -&gt;emailFormat('both')
              -&gt;config('default')
              -&gt;send('hi');
  
  }
  </code></pre>
  
  <p>Cake v2.3.1.</p>
  
  <p>Perhaps there is a different way to set multiple methods on this mocked function, but this was based upon a solution that somebody put online.</p>
  
  <p>(I know I shouldn't be sending email from here, but for this one registration function, I want to keep it here so that I can rollback transaction if the email does not get sent).</p>