Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't think PHPUnit supports partial mocks for the system under test. If you're trying to isolate methods then I'm sure your implementation works - I've done that too.</p> <p>However, I try to avoid doing this, for a couple of reasons. </p> <p>First, it couples your test very tightly to the internal implementation of the class. Do you really care whether a method called <code>doesLongRunningThing</code> was called, or is it more important that the "LongRunningThing" got done? </p> <p>Second, when I run into this it always makes me wonder whether I've got one class doing the job of two. An <em>extract class</em> refactoring might be in order. The testing becomes much easier if <code>doesLongRunningThing()</code> becomes its own class, even with a single method. </p> <p>I believe the solution is to inject the services your SUT depends on (http://en.wikipedia.org/wiki/Dependency_injection). This also makes the <code>DoesLongRunningThing</code> implementation more testable.</p> <p>Without jumping into interfaces, here's what I would do:</p> <pre><code>class DoesLongRunningThing { public function execute() { sleep(10); return "stuff"; } } class StuffDoer { protected $doesLongRunningThing; public function setLongRunningThinger(DoesLongRunningThing $obj) { $this-&gt;doesLongRunningThing = $obj; } public function doStuff() { return $this-&gt;doesLongRunningThing-&gt;execute(); } } </code></pre> <p>Now it's easy to mock:</p> <pre><code>class StuffDoerTestCase extends PHPUnit_Framework_TestCase { public function testStuffDoer() { $dlrtMock = $this-&gt;getMock('DoesLongRunningThing'); $dlrtMock-&gt;expects($this-&gt;any())-&gt;will($this-&gt;returnValue("test stuff")); $sd = new StuffDoer(); $sd-&gt;setLongRunningThinger($dlrtMock); $result = $sd-&gt;doStuff(); $this-&gt;assertEquals($result, "test stuff"); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload