Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Wherever you have <code>new XXX(...)</code> in a method under test, you are doomed. Extract the instantiation to a new method--<code>createSomeClass(...)</code>--of the same class. This allows you to create a partial mock of the class under test that returns a stubbed or mock value from the new method.</p> <pre><code>class someClass { public function someFoo($var) { $model = $this-&gt;createSomeClass(); // call method instead of using new model-&gt;someOtherFoo($var); } public function createSomeClass() { // now you can mock this method in the test return new someClass(); } public function someOtherFoo($var){ // some code which has to be mocked } } </code></pre> <p>In the test, mock <code>createSomeClass()</code> in the instance on which you call <code>someFoo()</code>, and mock <code>someOtherFoo()</code> in the instance that you return from the first mocked call.</p> <pre><code>function testSomeFoo() { // mock someOtherFoo() to ensure it gets the correct value for $arg $created = $this-&gt;getMock('someClass', array('someOtherFoo')); $created-&gt;expects($this-&gt;once()) -&gt;method('someOtherFoo') -&gt;with('foo'); // mock createSomeClass() to return the mock above $creator = $this-&gt;getMock('someClass', array('createSomeClass')); $creator-&gt;expects($this-&gt;once()) -&gt;method('createSomeClass') -&gt;will($this-&gt;returnValue($created)); // call someFoo() with the correct $arg $creator-&gt;someFoo('foo'); } </code></pre> <p>Keep in mind that because the instance is creating another instance of the same class, two instances will normally be involved. You could use the same mock instance here if it makes it clearer.</p> <pre><code>function testSomeFoo() { $fixture = $this-&gt;getMock('someClass', array('createSomeClass', 'someOtherFoo')); // mock createSomeClass() to return the mock $fixture-&gt;expects($this-&gt;once()) -&gt;method('createSomeClass') -&gt;will($this-&gt;returnValue($fixture)); // mock someOtherFoo() to ensure it gets the correct value for $arg $fixture-&gt;expects($this-&gt;once()) -&gt;method('someOtherFoo') -&gt;with('foo'); // call someFoo() with the correct $arg $fixture-&gt;someFoo('foo'); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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