title: how to mock a class and override a method
body: <p>I have this class I'm testing that's using Redis somewhere deeper:</p>
  
  <pre><code>&lt;?php
  
  class Publisher {
      function publish($message) {
          Redis::publish($message);
      }
  }
  
  class Foo {
      public function publishMessage() {
          $message = $this-&gt;generateMessage();
          $this-&gt;publish($message);
      }
  
      private function publish($message) {
          $this-&gt;getPublisher()-&gt;publish($message);
      }
  
      // below just for testing
      private $publisher;
  
      public function getPublisher() {
          if(empty($this-&gt;publisher) {
               return new Publisher();
          }
          return $this-&gt;publisher;
      }
  
      public function setPublisher($publisher) {
          $this-&gt;publisher = $publisher;
      }
  }
  </code></pre>
  
  <p>Now I don't know how to test this. Of course I don't want to test Redis. What I actually need to test is if the message send to Redis is what I expect. (I think)
  I could write a function that returns the message and is public. But I don't like that idea.
  Here in this example I made it possible to set the publisher so while testing I can just return another Publisher class.
  Instead of sending the message it would save it internally so I can later assert it.</p>
  
  <pre><code>class Publisher {
      public $message;
      function publish($message) {
          $this-&gt;message = $message;
      }
  }  
  </code></pre>
  
  <p>But then I don't know how to mock the Publisher class to change the method. Or I would have to inherit from the Publisher class.
  Also this way my tested class must contain code just for testing. Which I don't like either.</p>
  
  <p>How would I test this properly?
  A mocking library for Redis exists but does not support publish.</p>