Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your question is not very clear - but I assume you are asking how to use phpunit's mock objects to return a different value in different situations?</p> <p>PHPUnit's mock classes allow you specify a custom function (ie: a callback function/method) - which is practically unlimited in what it can do.</p> <p>In the below example, I created a mock IUrlStorage class that will return the next url in its storage each time it is called.</p> <pre><code>public function setUp() { parent::setUp(); $this-&gt;fixture = new UrlDisplayer(); //change this to however you create your object //Create a list of expected URLs for testing across all test cases $this-&gt;expectedUrls = array( 'key1' =&gt; 'http://www.example.com/url1/' , 'key2' =&gt; 'http://www.example.net/url2/' , 'key3' =&gt; 'http://www.example.com/url3/' ); } public function testUrlDisplayerDisplaysLatestUrls { //Init $mockStorage = $this-&gt;getMock('IUrlStorage'); $mockStorage-&gt;expects($this-&gt;any()) -&gt;method('getUrl') -&gt;will( $this-&gt;returnCallback(array($this, 'mockgetUrl')) ); reset($this-&gt;expectedUrls); //reset array before testing //Actual Tests $this-&gt;assertGreaterThan(0, count($this-&gt;expectedUrls)); foreach ( $this-&gt;expectedUrls as $key =&gt; $expected ) { $actual = $this-&gt;fixture-&gt;displayUrl($key); $this-&gt;assertEquals($expected, $actual); } } public function mockGetUrl($name) { $value = current($this-&gt;expectedUrls); next($this-&gt;expectedUrls); //Return null instead of false when end of array is reached return ($value === false) ? null : $value; } </code></pre> <hr> <p>Alternatively, sometimes it is easier to simply create a real class that mocks up the necessary functionality. This is especially easy with well defined and small interfaces.</p> <p>In this specific case, I would suggest using the below class instead:</p> <pre><code>class MockStorage implements IUrlStorage { protected $urls = array(); public function addUrl($name, $url) { $this-&gt;urls[$name] = $url; } public function getUrl($name) { if ( isset($this-&gt;urls[$name]) ) { return $this-&gt;urls[$name]; } return null; } } ?&gt; </code></pre> <p>Then in your unit test class you simply instantiate your fixture like below:</p> <pre><code>public function setUp() { $mockStorage = new MockStorage(); //Add as many expected URLs you want to test for $mockStorage-&gt;addUrl('name1', 'http://example.com'); //etc... $this-&gt;fixture = new UrlDisplayer($mockStorage); } </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