Sophie

Sophie

distrib > Fedora > 13 > i386 > media > updates-src > by-pkgid > 67e73f1d5aab77d9527dc4ff7b388cdb > files > 3

php-deepend-Mockery-0.6.3-2.fc13.src.rpm


  
  

  


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
        <title>README.markdown at master from padraic's mockery - GitHub</title>
    <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub" />
    <link rel="fluid-icon" href="http://github.com/fluidicon.png" title="GitHub" />

    <link href="http://assets2.github.com/stylesheets/bundle_common.css?c7cdfd1c0e6c146521c4e6c7a3e43ad28ce3df8f" media="screen" rel="stylesheet" type="text/css" />
<link href="http://assets2.github.com/stylesheets/bundle_github.css?c7cdfd1c0e6c146521c4e6c7a3e43ad28ce3df8f" media="screen" rel="stylesheet" type="text/css" />

    <script type="text/javascript" charset="utf-8">
      var GitHub = {}
      var github_user = null
      
    </script>
    <script src="http://assets0.github.com/javascripts/jquery/jquery-1.4.2.min.js?c7cdfd1c0e6c146521c4e6c7a3e43ad28ce3df8f" type="text/javascript"></script>
    <script src="http://assets0.github.com/javascripts/bundle_common.js?c7cdfd1c0e6c146521c4e6c7a3e43ad28ce3df8f" type="text/javascript"></script>
<script src="http://assets1.github.com/javascripts/bundle_github.js?c7cdfd1c0e6c146521c4e6c7a3e43ad28ce3df8f" type="text/javascript"></script>

        <script type="text/javascript" charset="utf-8">
      GitHub.spy({
        repo: "padraic/mockery"
      })
    </script>

    
  
    
  

  <link href="http://github.com/padraic/mockery/commits/master.atom" rel="alternate" title="Recent Commits to mockery:master" type="application/atom+xml" />

        <meta name="description" content="Mockery is a simple but flexible mock object framework for use in unit testing." />
    <script type="text/javascript">
      GitHub.nameWithOwner = GitHub.nameWithOwner || "padraic/mockery";
      GitHub.currentRef = 'master';
    </script>
  

            <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-3769691-2']);
      _gaq.push(['_trackPageview']);
      (function() {
        var ga = document.createElement('script');
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        ga.setAttribute('async', 'true');
        document.documentElement.firstChild.appendChild(ga);
      })();
    </script>

  </head>

  

  <body>
    

    
      <script type="text/javascript">
        var _kmq = _kmq || [];
        function _kms(u){
          var s = document.createElement('script'); var f = document.getElementsByTagName('script')[0]; s.type = 'text/javascript'; s.async = true;
          s.src = u; f.parentNode.insertBefore(s, f);
        }
        _kms('//i.kissmetrics.com/i.js');_kms('//doug1izaerwt3.cloudfront.net/406e8bf3a2b8846ead55afb3cfaf6664523e3a54.1.js');
      </script>
    

    

    

    

    <div class="subnavd" id="main">
      <div id="header" class="pageheaded">
        <div class="site">
          <div class="logo">
            <a href="http://github.com"><img src="/images/modules/header/logov3.png" alt="github" /></a>
          </div>
          
          <div class="topsearch">
  
    <form action="/search" id="top_search_form" method="get">
      <a href="/search" class="advanced-search tooltipped downwards" title="Advanced Search">Advanced Search</a>
      <input type="search" class="search my_repos_autocompleter" name="q" results="5" placeholder="Search&hellip;" /> <input type="submit" value="Search" class="button" />
      <input type="hidden" name="type" value="Everything" />
      <input type="hidden" name="repo" value="" />
      <input type="hidden" name="langOverride" value="" />
      <input type="hidden" name="start_value" value="1" />
    </form>
  
  
    <ul class="nav logged_out">
      
        <li><a href="http://github.com">Home</a></li>
        <li class="pricing"><a href="/plans">Pricing and Signup</a></li>
        <li><a href="http://github.com/explore">Explore GitHub</a></li>
        
        <li><a href="/blog">Blog</a></li>
      
      <li><a href="https://github.com/login">Login</a></li>
    </ul>
  
</div>

        </div>
      </div>

      
      
        
    <div class="site">
      <div class="pagehead repohead vis-public   ">
        <h1>
          <a href="/padraic">padraic</a> / <strong><a href="http://github.com/padraic/mockery">mockery</a></strong>
          
          
        </h1>

        
    <ul class="actions">
      

      
        <li class="for-owner" style="display:none"><a href="https://github.com/padraic/mockery/edit" class="minibutton btn-admin "><span><span class="icon"></span>Admin</span></a></li>
        <li>
          <a href="/padraic/mockery/toggle_watch" class="minibutton btn-watch " id="watch_button" style="display:none"><span><span class="icon"></span>Watch</span></a>
          <a href="/padraic/mockery/toggle_watch" class="minibutton btn-watch " id="unwatch_button" style="display:none"><span><span class="icon"></span>Unwatch</span></a>
        </li>
        
          
            <li class="for-notforked" style="display:none"><a href="/padraic/mockery/fork" class="minibutton btn-fork " id="fork_button" onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', '2f588faa82330df44a7bdfba350a0bc5214c41c9'); f.appendChild(s);f.submit();return false;"><span><span class="icon"></span>Fork</span></a></li>
            <li class="for-hasfork" style="display:none"><a href="#" class="minibutton btn-fork " id="your_fork_button"><span><span class="icon"></span>Your Fork</span></a></li>
          

          
          <li id="pull_request_item" class='ospr' style="display:none"><a href="/padraic/mockery/pull_request/" class="minibutton btn-pull-request "><span><span class="icon"></span>Pull Request</span></a></li>
          

          <li><a href="#" class="minibutton btn-download " id="download_button"><span><span class="icon"></span>Download Source</span></a></li>
        
      
      
      <li class="repostats">
        <ul class="repo-stats">
          <li class="watchers"><a href="/padraic/mockery/watchers" title="Watchers" class="tooltipped downwards">54</a></li>
          <li class="forks"><a href="/padraic/mockery/network" title="Forks" class="tooltipped downwards">4</a></li>
        </ul>
      </li>
    </ul>


        
  <ul class="tabs">
    <li><a href="http://github.com/padraic/mockery/tree/master" class="selected" highlight="repo_source">Source</a></li>
    <li><a href="http://github.com/padraic/mockery/commits/master" highlight="repo_commits">Commits</a></li>

    
    <li><a href="/padraic/mockery/network" highlight="repo_network">Network (4)</a></li>

    

    
      
      <li><a href="/padraic/mockery/issues" highlight="issues">Issues (4)</a></li>
    

    
      
      <li><a href="/padraic/mockery/downloads">Downloads (4)</a></li>
    

          
      <li><a href="http://wiki.github.com/padraic/mockery/">Wiki (1)</a></li>
    
    <li><a href="/padraic/mockery/graphs" highlight="repo_graphs">Graphs</a></li>

    <li class="contextswitch nochoices">
      <span class="toggle leftwards" >
        <em>Branch:</em>
        <code>master</code>
      </span>
    </li>
  </ul>

  <div style="display:none" id="pl-description"><p><em class="placeholder">click here to add a description</em></p></div>
  <div style="display:none" id="pl-homepage"><p><em class="placeholder">click here to add a homepage</em></p></div>

  <div class="subnav-bar">
  
  <ul>
    <li>
      <a href="#" class="dropdown">Switch Branches (4)</a>
      <ul>
        
          
          
            <li><a href="/padraic/mockery/blob/0.6/README.markdown" action="show">0.6</a></li>
          
        
          
            <li><strong>master &#x2713;</strong></li>
            
          
          
            <li><a href="/padraic/mockery/blob/prototype/README.markdown" action="show">prototype</a></li>
          
        
          
          
            <li><a href="/padraic/mockery/blob/testspy/README.markdown" action="show">testspy</a></li>
          
        
      </ul>
    </li>
    <li>
      <a href="#" class="dropdown ">Switch Tags (4)</a>
              <ul>
                      
              <li><a href="/padraic/mockery/blob/0.6.3/README.markdown">0.6.3</a></li>
            
                      
              <li><a href="/padraic/mockery/blob/0.6.2/README.markdown">0.6.2</a></li>
            
                      
              <li><a href="/padraic/mockery/blob/0.6.1/README.markdown">0.6.1</a></li>
            
                      
              <li><a href="/padraic/mockery/blob/0.6.0/README.markdown">0.6.0</a></li>
            
                  </ul>
      
    </li>
    <li>
    
    <a href="/padraic/mockery/branches" class="manage">Branch List</a>
    
    </li>
  </ul>
</div>

  
  
  
  
  



        
    <div id="repo_details" class="metabox clearfix">
      <div id="repo_details_loader" class="metabox-loader" style="display:none">Sending Request&hellip;</div>

      
        <div class="pledgie">
          <a href='http://pledgie.com/campaigns/3286'><img alt='Click here to lend your support to: mockery and make a donation at www.pledgie.com !' src='http://www.pledgie.com/campaigns/3286.png?skin_name=chrome' border='0' /></a>
        </div>
      

      <div id="repository_description" rel="repository_description_edit">
        
          <p>Mockery is a simple but flexible mock object framework for use in unit testing.
            <span id="read_more" style="display:none">&mdash; <a href="#readme">Read more</a></span>
          </p>
        
      </div>
      <div id="repository_description_edit" style="display:none;" class="inline-edit">
        <form action="/padraic/mockery/edit/update" method="post"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="2f588faa82330df44a7bdfba350a0bc5214c41c9" /></div>
          <input type="hidden" name="field" value="repository_description">
          <input type="text" class="textfield" name="value" value="Mockery is a simple but flexible mock object framework for use in unit testing.">
          <div class="form-actions">
            <button class="minibutton"><span>Save</span></button> &nbsp; <a href="#" class="cancel">Cancel</a>
          </div>
        </form>
      </div>

      
      <div class="repository-homepage" id="repository_homepage" rel="repository_homepage_edit">
        <p><a href="http://www.survivethedeepend.com" rel="nofollow">http://www.survivethedeepend.com</a></p>
      </div>
      <div id="repository_homepage_edit" style="display:none;" class="inline-edit">
        <form action="/padraic/mockery/edit/update" method="post"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="2f588faa82330df44a7bdfba350a0bc5214c41c9" /></div>
          <input type="hidden" name="field" value="repository_homepage">
          <input type="text" class="textfield" name="value" value="http://www.survivethedeepend.com">
          <div class="form-actions">
            <button class="minibutton"><span>Save</span></button> &nbsp; <a href="#" class="cancel">Cancel</a>
          </div>
        </form>
      </div>

      <div class="rule "></div>

            <div id="url_box" class="url-box">
        <ul class="clone-urls">
          
            
            <li id="http_clone_url"><a href="http://github.com/padraic/mockery.git" data-permissions="Read-Only">HTTP</a></li>
            <li id="public_clone_url"><a href="git://github.com/padraic/mockery.git" data-permissions="Read-Only">Git Read-Only</a></li>
          
        </ul>
        <input type="text" spellcheck="false" id="url_field" class="url-field" />
              <span style="display:none" id="url_box_clippy"></span>
      <span id="clippy_tooltip_url_box_clippy" class="clippy-tooltip tooltipped" title="copy to clipboard">
      <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
              width="14"
              height="14"
              class="clippy"
              id="clippy" >
      <param name="movie" value="http://assets0.github.com/flash/clippy.swf?v5"/>
      <param name="allowScriptAccess" value="always" />
      <param name="quality" value="high" />
      <param name="scale" value="noscale" />
      <param NAME="FlashVars" value="id=url_box_clippy&amp;copied=&amp;copyto=">
      <param name="bgcolor" value="#FFFFFF">
      <param name="wmode" value="opaque">
      <embed src="http://assets0.github.com/flash/clippy.swf?v5"
             width="14"
             height="14"
             name="clippy"
             quality="high"
             allowScriptAccess="always"
             type="application/x-shockwave-flash"
             pluginspage="http://www.macromedia.com/go/getflashplayer"
             FlashVars="id=url_box_clippy&amp;copied=&amp;copyto="
             bgcolor="#FFFFFF"
             wmode="opaque"
      />
      </object>
      </span>

        <p id="url_description">This URL has <strong>Read+Write</strong> access</p>
      </div>
    </div>


        

      </div><!-- /.pagehead -->

      









<script type="text/javascript">
  GitHub.currentCommitRef = 'master'
  GitHub.currentRepoOwner = 'padraic'
  GitHub.currentRepo = "mockery"
  GitHub.downloadRepo = '/padraic/mockery/archives/master'

  

  
</script>










  <div id="commit">
    <div class="group">
        
  <div class="envelope commit">
    <div class="human">
      
        <div class="message"><pre><a href="/padraic/mockery/commit/3464b36356a4494bd5a1b3c6b9569aa1776a701a">Merge branch '0.6'</a> </pre></div>
      

      <div class="actor">
        <div class="gravatar">
          
          <img src="http://www.gravatar.com/avatar/94a0e0f46ab92fc828436bea73c53583?s=140&d=http%3A%2F%2Fgithub.com%2Fimages%2Fgravatars%2Fgravatar-140.png" alt="" width="30" height="30"  />
        </div>
        <div class="name"><a href="/padraic">padraic</a> <span>(author)</span></div>
        <div class="date">
          <abbr class="relatize" title="2010-06-09 13:27:32">Wed Jun 09 13:27:32 -0700 2010</abbr>
        </div>
      </div>

      

    </div>
    <div class="machine">
      <span>c</span>ommit&nbsp;&nbsp;<a href="/padraic/mockery/commit/3464b36356a4494bd5a1b3c6b9569aa1776a701a" hotkey="c">3464b36356a4494bd5a1</a><br />
      <span>t</span>ree&nbsp;&nbsp;&nbsp;&nbsp;<a href="/padraic/mockery/tree/3464b36356a4494bd5a1b3c6b9569aa1776a701a" hotkey="t">c5a7d74b6617b95f66d4</a><br />
      
        <span>p</span>arent&nbsp;
        
        <a href="/padraic/mockery/tree/5b5905c68c670cf8a246290303e292e216abb1e4" hotkey="p">5b5905c68c670cf8a246</a>
      
        <span>p</span>arent&nbsp;
        
        <a href="/padraic/mockery/tree/3309d90075ca849367235088c61316cc486b8113" hotkey="p">3309d90075ca84936723</a>
      

    </div>
  </div>

    </div>
  </div>



  
    <div id="path">
      <b><a href="/padraic/mockery/tree/3464b36356a4494bd5a1b3c6b9569aa1776a701a">mockery</a></b> / README.markdown       <span style="display:none" id="clippy_1415">README.markdown</span>
      
      <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
              width="110"
              height="14"
              class="clippy"
              id="clippy" >
      <param name="movie" value="http://assets0.github.com/flash/clippy.swf?v5"/>
      <param name="allowScriptAccess" value="always" />
      <param name="quality" value="high" />
      <param name="scale" value="noscale" />
      <param NAME="FlashVars" value="id=clippy_1415&amp;copied=copied!&amp;copyto=copy to clipboard">
      <param name="bgcolor" value="#FFFFFF">
      <param name="wmode" value="opaque">
      <embed src="http://assets0.github.com/flash/clippy.swf?v5"
             width="110"
             height="14"
             name="clippy"
             quality="high"
             allowScriptAccess="always"
             type="application/x-shockwave-flash"
             pluginspage="http://www.macromedia.com/go/getflashplayer"
             FlashVars="id=clippy_1415&amp;copied=copied!&amp;copyto=copy to clipboard"
             bgcolor="#FFFFFF"
             wmode="opaque"
      />
      </object>
      

    </div>

    <div id="files">
      <div class="file">
        <div class="meta">
          <div class="info">
            <span class="icon"><img alt="Txt" height="16" src="http://assets1.github.com/images/icons/txt.png?96ee04ab294d254e7b9fcc6d88f2aea1d2c61e13" width="16" /></span>
            <span class="mode" title="File Mode">100644</span>
            
              <span>801 lines (575 sloc)</span>
            
            <span>30.012 kb</span>
          </div>
          <ul class="actions">
            
              <li><a id="file-edit-link" href="#" rel="/padraic/mockery/file-edit/__ref__/README.markdown">edit</a></li>
            
            <li><a href="/padraic/mockery/raw/3464b36356a4494bd5a1b3c6b9569aa1776a701a/README.markdown" id="raw-url">raw</a></li>
            
              <li><a href="/padraic/mockery/blame/3464b36356a4494bd5a1b3c6b9569aa1776a701a/README.markdown">blame</a></li>
            
            <li><a href="/padraic/mockery/commits/master/README.markdown">history</a></li>
          </ul>
        </div>
        
  <div id="readme" class="blob">
    <div class="wikistyle"><h1>Mockery</h1>

<p>Mockery is a simple but flexible PHP mock object framework for use in unit testing.
It is inspired by Ruby's flexmock and Java's Mockito, borowing elements from
both of their APIs.</p>

<p>Mockery is released under a New BSD License.</p>

<h2>Mock Objects</h2>

<p>In unit tests, mock objects simulate the behaviour of real objects. They are
commonly utilised to offer test isolation, to stand in for objects which do not
yet exist, or to allow for the exploratory design of class APIs without
requiring actual implementation.</p>

<p>The benefits of a mock object framework are to allow for the flexible generation
of such mock objects (and stubs). They allow the setting of expected method calls
and return values using a flexible API which is capable of capturing every
possible real object behaviour in way that is as close as possible to a
natural language description.</p>

<h2>Prerequisites</h2>

<p>Mockery requires PHP 5.3 which is its sole prerequisite.</p>

<h2>Installation</h2>

<p>The preferred installation method is via PEAR. Mockery is hosted by the
Survivethedeepend.com PEAR channel:</p>

<pre><code>pear channel-discover pear.survivethedeepend.com
pear install deepend/Mockery
</code></pre>

<p>The git repository hosts the development version in its master branch. You may
install this development version using:</p>

<pre><code>git clone git://github.com/padraic/mockery.git
cd mockery
sudo pear install package.xml
</code></pre>

<p>The above processes will install Mockery as a PEAR library.</p>

<h2>Simple Example</h2>

<p>Imagine we have a Temperature class which samples the temperature of a locale
before reporting an average temperature. The data could come from a web service
or any other data source, but we do not have such a class at present. We can,
however, assume some basic interactions with such a class based on its interaction
with the Temperature class.</p>

<pre><code>class Temperature
{

    public function __construct($service)
    {
        $this-&gt;_service = $service;
    }

    public function average()
    {
        $total = 0;
        for ($i=0;$i&lt;3;$i++) {
            $total += $this-&gt;_service-&gt;readTemp();
        }
        return $total/3;
    }

}
</code></pre>

<p>Even without an actual service class, we can see how we expect it to operate.
When writing a test for the Temperature class, we can now substitute a mock
object for the real service which allows us to test the behaviour of the
Temperature class without actually needing a concrete service instance.</p>

<p>Note: PHPUnit integration (see below) can remove the need for a teardown() method.</p>

<pre><code>use \Mockery as m;

class TemperatureTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        m::close();
    }

    public function testGetsAverageTemperatureFromThreeServiceReadings()
    {
        $service = m::mock('service');
        $service-&gt;shouldReceive('readTemp')-&gt;times(3)-&gt;andReturn(10, 12, 14);
        $temperature = new Temperature($service);
        $this-&gt;assertEquals(12, $temperature-&gt;average());
    }

}
</code></pre>

<p>We'll cover the API in greater detail below.</p>

<h2>PHPUnit Integration</h2>

<p>Mockery was designed as a simple to use standalone mock object framework, so
its need for integration with any testing framework is entirely optional.
To integrate Mockery, you just need to define a teardown() method for your
tests containing the following (you may use a shorter \Mockery namespace alias):</p>

<pre><code>public function teardown() {
    \Mockery::close();
}
</code></pre>

<p>This static call cleans up the Mockery container used by the current test, and
run any verification tasks needed for your expectations.</p>

<p>For some added brevity when it comes to using Mockery, you can also explicitly
use the Mockery namespace with a shorter alias. For example:</p>

<pre><code>use \Mockery as m;

class SimpleTest extends extends PHPUnit_Framework_TestCase
{
    public function testSimpleMock() {
        $mock = m::mock('simple mock');
        $mock-&gt;shouldReceive('foo')-&gt;with(5, m::any())-&gt;once()-&gt;andReturn(10);
        $this-&gt;assertEquals(10, $mock-&gt;foo(5));
    }

    public function teardown() {
        m::close();
    }
}
</code></pre>

<p>Mockery ships with an autoloader so you don't need to litter your tests with
require_once() calls. To use it, ensure Mockery is on your include_path and add
the following to your test suite's Bootstrap or TestHelper file:</p>

<pre><code>require_once 'Mockery/Loader.php';
$loader = new \Mockery\Loader;
$loader-&gt;register();
</code></pre>

<h2>Quick Reference</h2>

<p>Mockery implements a shorthand API when creating a mock. Here's a sampling
of the possible startup methods.</p>

<pre><code>$mock = \Mockery::mock('foo');
</code></pre>

<p>Creates a mock object named foo. In this case, foo is a name (not necessarily
a class name) used as a simple identifier when raising exceptions. This creates
a mock object of type \Mockery\Mock and is the loosest form of mock possible.</p>

<pre><code>$mock = \Mockery::mock(array('foo'=&gt;1,'bar'=&gt;2));
</code></pre>

<p>Creates an mock object named unknown since we passed no name. However we did
pass an expectation array, a quick method of setting up methods to expect with
their return values.</p>

<pre><code>$mock = \Mockery::mock('foo', array('foo'=&gt;1,'bar'=&gt;2));
</code></pre>

<p>Similar to the previous examples, only demonstrating the combination of a name
and expectation array.</p>

<pre><code>$mock = \Mockery::mock('stdClass');
</code></pre>

<p>Creates a mock identical to a named mock, except the name is an actual class
name. Creates a simple mock as previous examples show, except the mock
object will inherit the class type, i.e. it will pass type hints or instanceof
evaluations for stdClass. Useful where a mock object must be of a specific
type.</p>

<pre><code>$mock = \Mockery::mock('FooInterface');
</code></pre>

<p>You can create mock objects based on any concrete class, abstract class or
even an interface. Again, the primary purpose is to ensure the mock object
inherits a specific type for type hinting.</p>

<pre><code>$mock = \Mockery::mock('FooInterface', array('foo'=&gt;1,'bar'=&gt;2));
</code></pre>

<p>Yes, you can use the same quick expectation setup as for named mocks with the
class oriented mock object generation.</p>

<pre><code>$mock = \Mockery::mock(new Foo);
</code></pre>

<p>Passing any real object into Mockery will create a partial mock. Partials assume
you can already create a concrete object, so all we need to do is selectively
override a subset of existing methods (or add non-existing methods!) for
our expectations.</p>

<pre><code>$mock = \Mockery::mock(new Foo, array('foo'=&gt;1));
</code></pre>

<p>You can also use the quickie expectation setup for your partial mock. See the
section later on Creating Partial Mocks for more information.</p>

<pre><code>$mock = \Mockery::mock('name', function($mock){
    $mock-&gt;shouldReceive(method_name);
});
</code></pre>

<p>All of the various setup methods may be passed a closure as the final parameter.
The closure will be passed the mock object when called so that expectations
can be setup. Distinct from the later explained default expectations, this
allows for the reuse of expectation setups by storing them to a closure for
execution. Note that all other parameters including quick expectation arrays set
prior to the closure will be used before the closure is called.</p>

<h2>Expectation Declarations</h2>

<p>Once you have created a mock object, you'll often want to start defining how
exactly it should behave (and how it should be called). This is where the
Mockery expectation declarations take over.</p>

<pre><code>shouldReceive(method_name)
</code></pre>

<p>Declares that the mock expects a call to the given method name. This is the
starting expectation upon which all other expectations and constraints are
appended.</p>

<pre><code>shouldReceive(method1, method2, ...)
</code></pre>

<p>Declares a number of expected method calls, all of which will adopt any chained
expectations or constraints.</p>

<pre><code>shouldReceive(array(method1=&gt;1, method2=&gt;2, ...))
</code></pre>

<p>Declares a number of expected calls but also their return values. All will
adopt any additional chained expectations or constraints.</p>

<pre><code>shouldReceive(closure)
</code></pre>

<p>Creates a mock object (only from a partial mock) which is used to create a mock
object recorder. The recorder is a simple proxy to the original object passed
in for mocking. This is passed to the closure, which may run it through a set of
operations which are recorded as expectations on the partial mock. A simple
use case is automatically recording expectations based on an existing usage
(e.g. during refactoring). See examples in a later section.</p>

<pre><code>with(arg1, arg2, ...)
</code></pre>

<p>Adds a constraint that this expectation only applies to method calls which
match the expected argument list. You can add a lot more flexibility to argument
matching using the built in matcher classes (see later). For example,
\Mockery::any() matches any argument passed to that position in the with()
parameter list.</p>

<p>It's important to note that this means all expectations attached only apply
to the given method when it is called with these exact arguments. Allows for
setting up differing expectations based on the arguments provided to expected calls.</p>

<pre><code>withAnyArgs()
</code></pre>

<p>Declares that this expectation matches a method call regardless of what arguments
are passed. This is set by default unless otherwise specified.</p>

<pre><code>withNoArgs()
</code></pre>

<p>Declares this expectation matches method calls with zero arguments.</p>

<pre><code>andReturn(value)
</code></pre>

<p>Sets a value to be returned from the expected method call.</p>

<pre><code>andReturn(value1, value2, ...)
</code></pre>

<p>Sets up a sequence of return values or closures. For example, the first call will return
value1 and the second value2. Not that all subsequent calls to a mocked method
will always return the final value (or the only value) given to this declaration.</p>

<pre><code>andReturnUsing(closure, ...)
</code></pre>

<p>Sets a closure (anonymous function) to be called with the arguments passed to
the method. The return value from the closure is then returned. Useful for some
dynamic processing of arguments into related concrete results. Closures can
queued by passing them as extra parameters as for andReturn(). Note that you
cannot currently mix andReturnUsing() with andReturn().</p>

<pre><code>andThrow(Exception)
</code></pre>

<p>Declares that this method will throw the given Exception object when called.</p>

<pre><code>andThrow(exception_name, message)
</code></pre>

<p>Rather than an object, you can pass in the Exception class and message to
use when throwing an Exception from the mocked method.</p>

<pre><code>zeroOrMoreTimes()
</code></pre>

<p>Declares that the expected method may be called zero or more times. This is
the default for all methods unless otherwise set.</p>

<pre><code>once()
</code></pre>

<p>Declares that the expected method may only be called once. Like all other
call count constraints, it will throw a \Mockery\CountValidator\Exception
if breached and can be modified by the atLeast() and atMost() constraints.</p>

<pre><code>twice()
</code></pre>

<p>Declares that the expected method may only be called twice.</p>

<pre><code>times(n)
</code></pre>

<p>Declares that the expected method may only be called n times.</p>

<pre><code>never()
</code></pre>

<p>Declares that the expected method may never be called. Ever!</p>

<pre><code>atLeast()
</code></pre>

<p>Adds a minimum modifier to the next call count expectation. Thus
atLeast()->times(3) means the call must be called at least three times (given
matching method args) but never less than three times.</p>

<pre><code>atMost()
</code></pre>

<p>Adds a maximum modifier to the next call count expectation. Thus
atMost()->times(3) means the call must be called no more than three times. This
also means no calls are acceptable.</p>

<pre><code>between(min, max)
</code></pre>

<p>Sets an expected range of call counts. This is actually identical to using
atLeast()->times(min)->atMost()->times(max) but is provided as a shorthand.
It may be followed by a times() call with no parameter to preserve the
APIs natural language readability.</p>

<pre><code>ordered()
</code></pre>

<p>Declares that this method is expected to be called in a specific order in
relation to similarly marked methods. The order is dictated by the order in
which this modifier is actually used when setting up mocks.</p>

<pre><code>ordered(group)
</code></pre>

<p>Declares the method as belonging to an order group (which can be named or
numbered). Methods within a group can be called in any order, but the ordered
calls from outside the group are ordered in relation to the group, i.e. you can
set up so that method1 is called before group1 which is in turn called before
method 2.</p>

<pre><code>globally()
</code></pre>

<p>When called prior to ordered() or ordered(group), it declares this ordering to
apply across all mock objects (not just the current mock). This allows for dictating
order expectations across multiple mocks.</p>

<pre><code>byDefault()
</code></pre>

<p>Marks an expectation as a default. Default expectations are applied unless
a non-default expectation is created. These later expectations immediately
replace the previously defined default. This is useful so you can setup default
mocks in your unit test setup() and later tweak them in specific tests as
needed.</p>

<pre><code>mock()
</code></pre>

<p>Returns the current mock object from an expectation chain. Useful where
you prefer to keep mock setups as a single statement, e.g.</p>

<pre><code>$mock = \Mockery::mock('foo')-&gt;shouldReceive('foo')-&gt;andReturn(1)-&gt;mock();
</code></pre>

<h2>Argument Validation</h2>

<p>The arguments passed to the with() declaration when setting up an expectation
determine the criteria for matching method calls to expectations. Thus, you
can setup up many expectations for a single method, each differentiated by
the expected arguments. Such argument matching is done on a "best fit" basis.
This ensures explicit matches take precedence over generalised matches.</p>

<p>An explicit match is merely where the expected argument and the actual argument
are easily equated (i.e. using === or ==). More generalised matches are possible
using regular expressions, class hinting and the available generic matchers. The
purpose of generalised matchers is to allow arguments be defined in non-explicit
terms, e.g. Mockery::any() passed to with() will match ANY argument in that
position.</p>

<p>Here's a sample of the possibilities.</p>

<pre><code>with(1)
</code></pre>

<p>Matches the integer 1. This passes the === test (identical). It does facilitate
a less strict == check (equals) where the string '1' would also match the
argument.</p>

<pre><code>with(\Mockery::any())
</code></pre>

<p>Matches any argument. Basically, anything and everything passed in this argument
slot is passed unconstrained.</p>

<pre><code>with(\Mockery::type('resource'))
</code></pre>

<p>Matches any resource, i.e. returns true from an is_resource() call. The Type
matcher accepts any string which can be attached to "is_" to form a valid
type check. For example, \Mockery::type('float') checks using is_float() and
\Mockery::type('callable') uses is_callable(). The Type matcher also accepts
a class or interface name to be used in an instanceof evaluation of the
actual argument.</p>

<p>You may find a full list of the available type checkers at
http://www.php.net/manual/en/ref.var.php</p>

<pre><code>with(\Mockery::on(closure))
</code></pre>

<p>The On matcher accepts a closure (anonymous function) to which the actual argument
will be passed. If the closure evaluates to (i.e. returns) boolean TRUE then
the argument is assumed to have matched the expectation. This is invaluable
where your argument expectation is a bit too complex for or simply not
implemented in the current default matchers.</p>

<pre><code>with('/^foo/')
</code></pre>

<p>The argument declarator also assumes any given string may be a regular
expression to be used against actual arguments when matching. The regex option
is only used when a) there is no === or == match and b) when the regex
is verified to be a valid regex (i.e. does not return false from preg_match()).</p>

<pre><code>with(\Mockery::ducktype('foo', 'bar'))
</code></pre>

<p>The Ducktype matcher is an alternative to matching by class type. It simply
matches any argument which is an object containing the provided list
of methods to call.</p>

<pre><code>with(\Mockery::mustBe(2));
</code></pre>

<p>The MustBe matcher is more strict than the default argument matcher. The default
matcher allows for PHP type casting, but the MustBe matcher also verifies that
the argument must be of the same type as the expected value. Thus by default,
the argument '2' matches the actual argument 2 (integer) but the MustBe matcher
would fail in the same situation since the expected argument was a string and
instead we got an integer.</p>

<p>Note: Objects are not subject to an identical comparison using this matcher
since PHP would fail the comparison if both objects were not the exact same
instance. This is a hindrance when objects are generated prior to being
returned, since an identical match just would never be possible.</p>

<pre><code>with(\Mockery::not(2))
</code></pre>

<p>The Not matcher matches any argument which is not equal or identical to the
matcher's parameter.</p>

<pre><code>with(\Mockery::anyOf(1, 2))
</code></pre>

<p>Matches any argument which equals any one of the given parameters.</p>

<pre><code>with(\Mockery::notAnyof(1, 2))
</code></pre>

<p>Matches any argument which is not equal or identical to any of the given
parameters.</p>

<pre><code>with(\Mockery::subset(array(0=&gt;'foo')))
</code></pre>

<p>Matches any argument which is any array containing the given array subset. This
enforces both key naming and values, i.e. both the key and value of each
actual element is compared.</p>

<pre><code>with(\Mockery::contains(value1, value2))
</code></pre>

<p>Matches any argument which is an array containing the listed values. The naming
of keys is ignored.</p>

<pre><code>with(\Mockery::hasKey(key));
</code></pre>

<p>Matches any argument which is an array containing the given key name.</p>

<pre><code>with(\Mockery::hasValue(value));
</code></pre>

<p>Matches any argument which is an array containing the given value.</p>

<h2>Creating Partial Mocks</h2>

<p>Partial mocks are useful when you only need to mock several methods of an object
leaving the remainder free to respond to calls normally (i.e. as implemented).</p>

<p>Unlike other mock objects, a Mockery partial mock has a real concrete object
at its heart. This approach to partial mocks is intended to bypass a number
of troublesome issues with partials. For example, partials might require
constructor parameters and other setup/injection tasks prior to use. Trying
to perform this automatically via Mockery is not a tenth as intuitive as just
doing it normally - and then passing the object into Mockery.</p>

<p>Partial mocks are therefore constructed as a Proxy with an embedded real object.
The Proxy itself inherits the type of the embedded object (type safety) and
it otherwise behaves like any other Mockery-based mock object, allowing you to
dynamically define expectations. This flexibility means there's little
upfront defining (besides setting up the real object) and you can set defaults,
expectations and ordering on the fly.</p>

<h2>Default Mock Expectations</h2>

<p>Often in unit testing, we end up with sets of tests which use the same object
dependency over and over again. Rather than mocking this class/object within
every single unit test (requiring a mountain of duplicate code), we can instead
define reusable default mocks within the test case's setup() method. This even
works where unit tests use varying expectations on the same or similar mock
object.</p>

<p>How this works, is that you can define mocks with default expectations. Then,
in a later unit test, you can add or fine-tune expectations for that
specific test. Any expectation can be set as a default using the byDefault()
declaration.</p>

<h2>Mocking Demeter Chains And Fluent Interfaces</h2>

<p>Both of these terms refer to the growing practice of invoking statements
similar to:</p>

<pre><code>$object-&gt;foo()-&gt;bar()-&gt;zebra()-&gt;alpha()-&gt;selfDestruct();
</code></pre>

<p>The long chain of method calls isn't necessarily a bad thing, assuming they
each link back to a local object the calling class knows. Just as a fun example,
Mockery's long chains (after the first shouldReceive() method) all call to the
same instance of \Mockery\Expectation. However, sometimes this is not the case
and the chain is constantly crossing object boundaries.</p>

<p>In either case, mocking such a chain can be a horrible task. To make it easier
Mockery support demeter chain mocking. Essentially, we shortcut through the
chain and return a defined value from the final call. For example, let's
assume selfDestruct() returns the string "Ten!" to $object (an instance of
CaptainsConsole). Here's how we could mock it.</p>

<pre><code>$mock = \Mockery::mock('CaptainsConsole');
$mock-&gt;shouldReceive('foo-&gt;bar-&gt;zebra-&gt;alpha-&gt;selfDestruct')-&gt;andReturn('Ten!');
</code></pre>

<p>The above expectation can follow any previously seen format or expectation, except
that the method name is simply the string of all expected chain calls separated
by "->". Mockery will automatically setup the chain of expected calls with
its final return values, regardless of whatever intermediary object might be
used in the real implementation.</p>

<p>Arguments to all members of the chain (except the final call) are ignored in
this process.</p>

<h2>Mock Object Recording</h2>

<p>In certain cases, you may find that you are testing against an already
established pattern of behaviour, perhaps during refactoring. Rather then hand
crafting mock object expectations for this behaviour, you could instead use
the existing source code to record the interactions a real object undergoes
onto a mock object as expectations - expectations you can then verify against
an alternative or refactored version of the source code.</p>

<p>To record expectations, you need a concrete instance of the class to be mocked.
This can then be used to create a partial mock to which is given the necessary
code to execute the object interactions to be recorded. A simple example is
outline below (we use a closure for passing instructions to the mock).</p>

<p>Here we have a very simple setup, a class (SubjectUser) which uses another class
(Subject) to retrieve some value. We want to record as expectations on our
mock (which will replace Subject later) all the calls and return values of
a Subject instance when interacting with SubjectUser.</p>

<pre><code>class Subject {

    public function execute() {
        return 'executed!';
    }
}

class SubjectUser {

    public function use(Subject $subject) {
        return $subject-&gt;execute();
    }
}
</code></pre>

<p>Here's the test case showing the recording:</p>

<pre><code>class SubjectUserTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        \Mockery::close();
    }

    public function testSomething()
    {
        $mock = \Mockery::mock(new Subject);
        $mock-&gt;shouldExpect(function ($subject) {
            $user = new SubjectUser;
            $user-&gt;use($subject);
        });

        /**
         * Assume we have a replacement SubjectUser called NewSubjectUser.
         * We want to verify it behaves identically to SubjectUser, i.e.
         * it uses Subject in the exact same way
         */
        $newSubject = new NewSubjectUser;
        $newSubject-&gt;use($mock);
    }

}
</code></pre>

<p>After the \Mockery::close() call in teardown() validates the mock object, we
should have zero exceptions if NewSubjectUser acted on Subject in a similar way
to SubjectUser. By default the order of calls are not enforced, and loose argument
matching is enabled, i.e. arguments may be equal (==) but not necessarily identical
(===).</p>

<p>If you wished to be more strict, for example ensuring the order of calls
and the final call counts were identical, or ensuring arguments are completely
identical, you can invoke the recorder's strict mode from the closure block, e.g.</p>

<pre><code>$mock-&gt;shouldExpect(function ($subject) {
    $subject-&gt;shouldBeStrict();
    $user = new SubjectUser;
    $user-&gt;use($subject);
});
</code></pre>

<h2>Dealing with Final Classes/Methods</h2>

<p>One of the primary restrictions of mock objects in PHP, is that mocking classes
or methods marked final is hard. The final keyword prevents methods so marked
from being replaced in subclasses (subclassing is how mock objects can inherit
the type of the class or object being mocked.</p>

<p>The simplest solution is not to mark classes or methods as final!</p>

<p>However, in a compromise between mocking functionality and type safety, Mockery
does allow creating partial mocks from classes marked final, or from classes with
methods marked final. This offers all the usual mock object goodness but the
resulting mock will not inherit the class type of the object being mocked, i.e.
it will not pass any instanceof comparison.</p>

<h2>Mockery Global Configuration</h2>

<p>To allow for a degree of fine-tuning, Mockery utilises a singleton configuration
object to store a small subset of core behaviours. The two currently present
include:</p>

<ul>
<li>Allowing the mocking of methods which do not actually exist</li>
<li>Allowing the existence of expectations which are never fulfilled (i.e. unused)</li>
</ul>


<p>By default, these behaviours are enabled. Of course, there are situations where
this can lead to unintended consequences. The mocking of non-existent methods
may allow mocks based on real classes/objects to fall out of sync with the
actual implementations, especially when some degree of integration testing (testing
of object wiring) is not being performed. Allowing unfulfilled expectations means
unnecessary mock expectations go unnoticed, cluttering up test code, and
potentially confusing test readers.</p>

<p>You may allow or disallow these behaviours (whether for whole test suites or just
select tests) by using one or both of the following two calls:</p>

<pre><code>\Mockery::getConfiguration()-&gt;allowMockingNonExistentMethods(bool);
\Mockery::getConfiguration()-&gt;allowMockingMethodsUnnecessarily(bool);
</code></pre>

<p>Passing a true allows the behaviour, false disallows it. Both take effect
immediately until switched back. In both cases, if either
behaviour is detected when not allowed, it will result in an Exception being
thrown at that point. Note that disallowing these behaviours should be carefully
considered since they necessarily remove at least some of Mockery's flexibility.</p>

<h2>Reserved Method Names</h2>

<p>As you may have noticed, Mockery uses a number of methods called directly on
all mock objects, for example shouldReceive(). Such methods are necessary
in order to setup expectations on the given mock, and so they cannot be
implemented on the classes or objects being mocked without creating a method
name collision (reported as a PHP fatal error). The methods reserved by Mockery are:</p>

<ul>
<li>shouldReceive()</li>
<li>shouldBeStrict()</li>
</ul>


<p>In addition, all mocks utilise a set of added methods and protected properties
which cannot exist on the class or object being mocked. These are far less likely
to cause collisions. All properties are prefixed with "<em>mockery" and all method
names with "mockery</em>".</p>

<h2>Quick Examples</h2>

<p>Create a mock object to return a sequence of values from a set of method calls.</p>

<pre><code>class SimpleTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        \Mockery::close();
    }

    public function testSimpleMock()
    {
        $mock = \Mockery::mock(array('pi' =&gt; 3.1416, 'e' =&gt; 2.71));
        $this-&gt;assertEquals(3.1416, $mock-&gt;pi());
        $this-&gt;assertEquals(2.71, $mock-&gt;e());
    }

}
</code></pre>

<p>Create a mock object which returns a self-chaining Undefined object for a method
call.</p>

<pre><code>use \Mockery as m;

class UndefinedTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        m::close();
    }

    public function testUndefinedValues()
    {
        $mock = m::mock('my mock');
        $mock-&gt;shouldReceive('divideBy')-&gt;with(0)-&gt;andReturnUndefined();
        $this-&gt;assertTrue($mock-&gt;divideBy(0) instanceof \Mockery\Undefined);
    }

}
</code></pre>

<p>Creates a mock object which multiple query calls and a single update call</p>

<pre><code>use \Mockery as m;

class DbTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        m::close();
    }

    public function testDbAdapter()
    {
        $mock = m::mock('db');
        $mock-&gt;shouldReceive('query')-&gt;andReturn(1, 2, 3);
        $mock-&gt;shouldReceive('update')-&gt;with(5)-&gt;andReturn(NULL)-&gt;once();

        // test code here using the mock
    }

}
</code></pre>

<p>Expect all queries to be executed before any updates.</p>

<pre><code>use \Mockery as m;

class DbTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        m::close();
    }

    public function testQueryAndUpdateOrder()
    {
        $mock = m::mock('db');
        $mock-&gt;shouldReceive('query')-&gt;andReturn(1, 2, 3)-&gt;ordered();
        $mock-&gt;shouldReceive('update')-&gt;andReturn(NULL)-&gt;once()-&gt;ordered();

        // test code here using the mock
    }

}
</code></pre>

<p>Create a mock object where all queries occur after startup, but before finish, and
where queries are expected with several different params.</p>

<pre><code>use \Mockery as m;

class DbTest extends extends PHPUnit_Framework_TestCase
{

    public function teardown()
    {
        m::close();
    }

    public function testOrderedQueries()
    {
        $db = m::mock('db');
        $db-&gt;shouldReceive('startup')-&gt;once()-&gt;ordered();
        $db-&gt;shouldReceive('query')-&gt;with('CPWR')-&gt;andReturn(12.3)-&gt;once()-&gt;ordered('queries');
        $db-&gt;shouldReceive('query')-&gt;with('MSFT')-&gt;andReturn(10.0)-&gt;once()-&gt;ordered('queries');
        $db-&gt;shouldReceive('query')-&gt;with("/^....$/")-&gt;andReturn(3.3)-&gt;atLeast()-&gt;once()-&gt;ordered('queries');
        $db-&gt;shouldReceive('finish')-&gt;once()-&gt;ordered();

        // test code here using the mock
    }

}
</code></pre>
</div>
  </div>


      </div>
    </div>

  


    </div>
  
      

      <div class="push"></div>
    </div>

    <div id="footer">
      <div class="site">
        <div class="info">
          <div class="links">
            <a href="http://github.com/blog"><b>Blog</b></a> |
            <a href="http://support.github.com">Support</a> |
            <a href="http://github.com/training">Training</a> |
            <a href="http://github.com/contact">Contact</a> |
            <a href="http://develop.github.com">API</a> |
            <a href="http://status.github.com">Status</a> |
            <a href="http://twitter.com/github">Twitter</a> |
            <a href="http://help.github.com">Help</a> |
            <a href="http://github.com/security">Security</a>
          </div>
          <div class="company">
            &copy;
            2010
            <span id="_rrt" title="0.07521s from fe4.rs.github.com">GitHub</span> Inc.
            All rights reserved. |
            <a href="/site/terms">Terms of Service</a> |
            <a href="/site/privacy">Privacy Policy</a>
          </div>
        </div>
        <div class="sponsor">
          <div>
            Powered by the <a href="http://www.rackspace.com ">Dedicated
            Servers</a> and<br/> <a href="http://www.rackspacecloud.com">Cloud
            Computing</a> of Rackspace Hosting<span>&reg;</span>
          </div>
          <a href="http://www.rackspace.com">
            <img alt="Dedicated Server" src="http://assets1.github.com/images/modules/footer/rackspace_logo.png?c7cdfd1c0e6c146521c4e6c7a3e43ad28ce3df8f" />
          </a>
        </div>
      </div>
    </div>

    
    
      <!-- current locale:  -->
      <div class="locales">
        <div class="site">
          <ul class="choices">
            
              
                <li><span class="current">English</span></li>
              
            
              
                
                  <li><a rel="nofollow" href="?locale=ca">Català</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=cs">Čeština</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=de">Deutsch</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=es">Español</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=fr">Français</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=hr">Hrvatski</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=id">Indonesia</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=it">Italiano</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=ja">日本語</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=nl">Nederlands</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=no">Norsk</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=pl">Polski</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=pt-BR">Português (BR)</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=sr">Српски</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=sv">Svenska</a></li>
                
              
            
              
                
                  <li><a rel="nofollow" href="?locale=zh">中文</a></li>
                
              
            
          </ul>
        </div>
      </div>
    

    <script>window._auth_token = "2f588faa82330df44a7bdfba350a0bc5214c41c9"</script>
    

    <script type="text/javascript">
      _kmq.push(['trackClick', 'entice_banner_link', 'Entice banner clicked']);
      
    </script>
    
  </body>
</html>