Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Mockery rewrite - back to basics ;)

  • Loading branch information...
commit 20f2b018a6ca692a571dce160baad344c9292903 1 parent c2f838d
Padraic Brady authored
Showing with 309 additions and 2,661 deletions.
  1. +3 −0  .gitignore
  2. +27 −0 LICENSE
  3. +0 −98 README
  4. +0 −274 build/build.xml
  5. +0 −22 examples/temp/library/TemperatureSampler.php
  6. +0 −23 examples/temp/tests/TemperatureSamplerTest.php
  7. +0 −222 library/Mockery.php
  8. +0 −23 library/Mockery/AtLeastCounter.php
  9. +0 −23 library/Mockery/AtMostCounter.php
  10. +0 −52 library/Mockery/Director.php
  11. +0 −6 library/Mockery/Exception.php
  12. +0 −239 library/Mockery/Expectation.php
  13. +0 −6 library/Mockery/ExpectationException.php
  14. +0 −26 library/Mockery/Framework.php
  15. +138 −0 library/Mockery/Loader.php
  16. +0 −93 library/Mockery/Mockery.php
  17. +0 −26 library/Mockery/StandardCounter.php
  18. +0 −42 library/Mockery/Store.php
  19. +0 −21 library/Mockery/Stub.php
  20. +0 −67 library/Mockery/Templates/Methods
  21. +0 −16 library/Mockery/ZeroOrMoreCounter.php
  22. +0 −33 tests/AllTests.php
  23. +77 −0 tests/Bootstrap.php
  24. +0 −2  tests/Mockery/.gitignore
  25. +46 −0 tests/Mockery/LoaderTest.php
  26. +0 −527 tests/MockeryExpectationsTest.php
  27. +0 −124 tests/MockeryTest.php
  28. +0 −32 tests/RegressionTest.php
  29. +0 −527 tests/StubExpectationsTest.php
  30. +0 −52 tests/TestHelper.php
  31. +0 −85 tests/_files/Album.php
  32. +18 −0 tests/phpunit.xml
View
3  .gitignore
@@ -0,0 +1,3 @@
+*~
+pearfarm.spec
+package.xml
View
27 LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2010, Pádraic Brady
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * The name of Pádraic Brady may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
98 README
@@ -1,98 +0,0 @@
-Mockery is a Cross Framework Mock Object and Stub Framework for PHP5, currently
-released as an alpha version for interested developers to assist in offering
-feedback. It is not yet fully functional, and stability is a relative term :).
-
-Requirements:
-
-PHP: 5.2.4, probably less but I haven't checked
-
-Installation (Manual Installation without PEAR):
-
-1. Copy the contents of /library to a location on the PHP include_path, e.g.
- /usr/share/php.
-
-Yeah, that's pretty much it :).
-
-Usage:
-
-Mockery defines two functions called mockery() and mockery_verify() which are a shorter
-means to call Mockery::mock() and Mockery::verify() which are both static methods. A simple
-use case is as follows:
-
-require_once 'Mockery/Framework.php';
-
-class Addition {
-
- protected $math = null;
-
- public function __construct(Math $math) {
- $this->math = $math;
- }
-
- public function add($op1, $op2) {
- return $this->math->add($op1, $op2);
- }
-
-}
-
-class Math {
-
- public function add($a, $b) {
- return $a + $b;
- }
-
-}
-
-class AdditionTest extends PHPUnit_Framework_TestCase {
-
- public function testAdd() {
- $math = mockery('Math');
- $addition = new Addition($math);
-
- // set Mock expectations!
- $math->shouldReceive('add')->once()->with(1, 1)->andReturn(2);
- // perform the action!
- $result = $addition->add(1, 1);
-
- // Verify?
- mockery_verify();
-
- // Proceed to assertions (if any) as normal
- $this->assertEqual(2, $result);
- }
-
- public function testAddWithFailingMock() {
- $math = mockery('Math');
- $addition = new Addition($math);
-
- // set Mock expectations!
- // twice() is obviously wrong
- $math->shouldReceive('add')->twice()->with(1, 1)->andReturn(2);
- // perform the action!
- $result = $addition->add(1, 1);
-
- // Verify?
- mockery_verify();
-
- // Proceed to assertions (if any) as normal
- $this->assertEqual(2, $result);
- }
-
-}
-
-PHPUnit reports:
-
-PHPUnit 3.3.14 by Sebastian Bergmann.
-
-.E
-
-Time: 0 seconds
-
-There was 1 error:
-
-1) testAddWithFailingMock(AdditionTest)
-Mockery_ExpectationException: method add called incorrect number of times;
-expected call 2 times but received 1
-
-A vastly more detailed introduction including brief API documentation is available on my blog:
-http://blog.astrumfutura.com/archives/392-The-Mockery-An-Independent-Mock-Object-and-Stub-Framework-for-PHP5.html
View
274 build/build.xml
@@ -1,274 +0,0 @@
-<?xml version="1.0"?>
-
-<!--
-
-Phing Usage:
-
- phing [ <options> ] [ <targetnames> ]
-
- example:
-
- phing dist ...where "dist" is the target for execution
-
-Phing Targets:
-
- prepare: Creates any necessary staging directories (has .pear suffix option)
-
- build: Prepares and stages files (has .pear suffix option)
-
- stage: Stages files either copying or exporting to staging directory (has .pear suffix option)
-
- dist: Stages and packages files to zip and gzip tarball and PEAR TGZ package
-
- pearify: Create a pear package.xml and source code directory tree
-
- docs: Generates the HTML manual only
-
- clean: Cleans up, deletes staging directories, returns to state 0
-
-Other Targets:
-
- src.check: Check for the existence of local source code
-
- svn.export: Export the source code from subversion
-
--->
-
-<project name="MockMe" default="dist" basedir=".">
-
- <taskdef classname="phing.tasks.ext.d51PearPkg2Task" name="d51pearpkg2" />
- <!--taskdef classname="phing.tasks.ext.PhpDocbookHighlighterTask" name="phpdocbookhighlighter" /-->
-
- <property name="spec.src.default" value="${project.basedir}/.." />
- <property name="spec.src.classpath" value="/library" />
- <property name="spec.name" value="Mockery" />
- <property name="spec.version" value="0.1.0alpha" /> <!-- VERSION FOR EDITING -->
- <property name="spec.stability" value="alpha" />
- <property name="spec.stage" value="${project.basedir}/stage" />
- <property name="spec.pear" value="${project.basedir}/stage-pear" />
- <property name="spec.stage.dir" value="${spec.stage}/${spec.name}-${spec.version}" />
- <property name="spec.pear.dir" value="${spec.pear}/${spec.name}-${spec.version}" />
- <property name="spec.pear.package" value="${spec.name}-${spec.version}.tgz" />
- <property name="spec.dist" value="${project.basedir}/dist" />
- <property name="spec.dist.pear" value="${spec.dist}/PEAR" />
- <property name="spec.tarball" value="${spec.stage}/${spec.name}-${spec.version}.tar" />
- <property name="spec.tarball.pear" value="${spec.stage}/${spec.name}-${spec.version}.tgz" />
- <property name="spec.zipball" value="${spec.stage}/${spec.name}-${spec.version}.zip" />
- <property name="lang" value="en" />
- <property name="languages" value="en" /> <!-- Add additional manual languages here -->
- <php expression="date('Y-m-d')" returnProperty="date"/>
-
- <property name="spec.manual" value="${project.basedir}/stage-manual" />
- <property name="spec.manual.dir" value="${spec.manual}/docbook" />
- <property name="spec.dist.manual" value="${spec.dist}/manual" />
-
- <property name="docbookxslurl" value="http://docbook.sourceforge.net/release/xsl/current/html/chunk.xsl" />
- <property name="docbookdtdurl" value="http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" />
- <property file="build.properties" override="true" />
-
- <target name="build" depends="prepare, prepare.pear, stage, stage.pear">
- </target>
-
- <target name="build.pear" depends="prepare.pear, stage.pear">
- </target>
-
- <target name="build.manual" depends="prepare.manual, stage.manual">
- </target>
-
- <target name="src.check">
- <available file="${spec.src.default}/library/Mockery/Framework.php" property="spec.src" value="${spec.src.default}" />
- <!--svnlastrevision svnpath="svn" repositoryurl="${spec.svn.url}" workingcopy="${project.basedir}" propertyname="spec.svn.revision" /-->
- </target>
-
- <target name="prepare" depends="src.check, prepare.dist">
- <echo msg="Making directory ${spec.stage}" />
- <mkdir dir="${spec.stage}" />
- <echo msg="Making directory ${spec.stage.dir}" />
- <mkdir dir="${spec.stage.dir}" />
- </target>
-
- <target name="prepare.pear" depends="src.check, prepare.dist">
- <echo msg="Making directory ${spec.pear}" />
- <mkdir dir="${spec.pear}" />
- <echo msg="Making directory ${spec.pear.dir}" />
- <mkdir dir="${spec.pear.dir}" />
- </target>
-
- <target name="prepare.dist">
- <echo msg="Making Distribution Files directory ${spec.dist}" />
- <mkdir dir="${spec.dist}" />
- <mkdir dir="${spec.dist.pear}" />
- </target>
-
- <target name="prepare.manual" depends="src.check">
- <echo msg="Making Manual directory ${spec.manual}" />
- <mkdir dir="${spec.manual}" />
- <echo msg="Making directory ${spec.manual.dir}" />
- <mkdir dir="${spec.manual.dir}" />
-
- <mkdir dir="${spec.dist.manual}" />
- </target>
-
- <target name="svn.export" unless="spec.src">
- <svnexport svnpath="svn" repositoryurl="${spec.svn.url}" todir="${spec.svn.export}" />
- <property name="spec.src" value="${spec.svn.export}" />
- </target>
-
- <target name="stage" depends="prepare, svn.export">
- <echo msg="Staging files from ${spec.src} to ${spec.stage.dir} for Standard Packaging" />
- <copy todir="${spec.stage.dir}">
- <fileset dir="${spec.src}">
- <exclude name="**/.**/**" />
- <exclude name="build/**" />
- <exclude name="docs/**" />
- </fileset>
- </copy>
- </target>
-
- <target name="stage.pear" depends="prepare.pear, svn.export">
- <echo msg="Staging files from ${spec.src} to ${spec.pear.dir} for PEAR Packaging" />
- <copy todir="${spec.pear.dir}">
- <fileset dir="${spec.src}">
- <exclude name="**/.**/**" />
- <exclude name="build/**" />
- <exclude name="docs/**" />
- <exclude name="library/**" />
- </fileset>
- </copy>
- <copy todir="${spec.pear.dir}">
- <fileset dir="${spec.src}${spec.src.classpath}">
- <exclude name="**/.**/**" />
- </fileset>
- </copy>
- </target>
-
- <target name="stage.manual" depends="prepare.manual, svn.export">
- <echo msg="Staging files from ${spec.src} to ${spec.manual.dir} for DocBook > HTML generation" />
- <copy todir="${spec.manual.dir}">
- <filterchain>
- <replacetokens>
- <token key="DOCBOOK_XSL" value="${docbookxslurl}" />
- <token key="DOCBOOK_DTD" value="${docbookdtdurl}" />
- </replacetokens>
- </filterchain>
- <fileset dir="${spec.src}/docs/manual">
- </fileset>
- </copy>
- </target>
-
- <target name="pearify" depends="build.pear">
- <d51pearpkg2 baseinstalldir="/" dir="${spec.pear.dir}">
-
- <name>Mockery</name>
- <summary>A cross framework Mock Object and Stubbing Framework for PHP5</summary>
- <channel>pear.php.net</channel>
- <description>
- Note: This is an alpha release for testing and feedback.
-
-
- </description>
-
- <date>${date}</date>
-
- <lead user="padraic" name="Pádraic Brady" email="padraic@php.net" />
- <license>New BSD</license>
-
- <version release="${spec.version}" api="${spec.version}" />
- <stability release="${spec.stability}" api="${spec.stability}" />
-
- <dependencies>
- <php minimum_version="5.2.3" />
- <pear minimum_version="1.6.0" />
- </dependencies>
-
- <dirroles key="bin">script</dirroles>
- <dirroles key="tests">test</dirroles>
- <dirroles key="specs">test</dirroles>
- <dirroles key="docs">doc</dirroles>
-
- <changelog version="0.1.0alpha" date="2009-03-05" license="New BSD">
- This is an ALPHA release for testing and
- feedback only.
- </changelog>
-
- </d51pearpkg2>
- </target>
-
- <target name="dist" depends="build, pearify">
- <echo message="Creating tar and zip archives..." />
- <tar destfile="${spec.tarball}.gz" basedir="${spec.stage.dir}" compression="gzip" />
- <move file="${spec.tarball}.gz" todir="${spec.dist}" overwrite="true" />
-
- <echo message="ZIP archive creation is disabled in build.xml file" />
- <!--zip destfile="${spec.zipball}" basedir="${spec.stage.dir}" /-->
- <!--move file="${spec.zipball}" todir="${spec.dist}" overwrite="true" /-->
-
- <echo message="Creating PEAR Package..." />
- <exec command="pear package" dir="${spec.pear.dir}" />
- <move file="${spec.pear.dir}/${spec.pear.package}" todir="${spec.dist.pear}" overwrite="true" />
- </target>
-
- <target name="clean">
- <delete dir="${spec.stage}" />
- <delete dir="${spec.pear}" />
- <delete dir="${spec.dist}" />
- <delete dir="${spec.manual}" />
- </target>
-
- <target name="install" depends="dist">
- <exec command="pear install ${spec.pear.package}" dir="${spec.dist.pear}" />
- </target>
-
- <target name="install.force" depends="dist">
- <exec command="pear install --force ${spec.pear.package}" dir="${spec.dist.pear}" />
- </target>
-
- <target name="docs" depends="build.manual">
- <echo msg="Rendering manual..." />
- <foreach list="${languages}" param="lang" target="docs.lang" />
- <echo msg="Manual has been rendered." />
- <echo msg="Rendering API Docs..." />
- <mkdir dir="${spec.dist.manual}/apidocs" />
- <phpdoc title="Mockery API Documentation"
- destdir="${spec.dist.manual}/apidocs"
- sourcecode="${spec.src}/src"
- output="HTML:frames:DOM/earthli">
- <fileset dir="${spec.src}/src">
- <include name="**" />
- </fileset>
- </phpdoc>
- <echo msg="API Docs have been rendered." />
- </target>
-
- <target name="docs.lang">
- <echo msg="Rendering ${lang} language manual." />
- <copy file="${spec.manual.dir}/${lang}/html/style.css" todir="${spec.dist.manual}/${lang}" />
- <mkdir dir="${spec.dist.manual}/${lang}/images" />
- <copy file="${spec.manual.dir}/${lang}/images/note.png" todir="${spec.dist.manual}/${lang}/images" />
- <copy todir="${spec.dist.manual}/${lang}/">
- <filterchain>
- <xincludefilter basedir="${spec.manual.dir}/${lang}/" />
- <xsltfilter style="${spec.manual.dir}/${lang}/html.xsl">
- <param name="base.dir" expression="${spec.dist.manual}/${lang}/" />
- </xsltfilter>
- </filterchain>
- <fileset dir="${spec.manual.dir}/${lang}/">
- <include name="manual.xml" />
- </fileset>
- </copy>
- <phpdocbookhighlighter dir="${spec.dist.manual}/${lang}/" />
- <echo msg="Manual for ${lang} language has been rendered." />
- </target>
-
- <target name="dist.docs" depends="docs">
- <copy todir="${spec.stage.dir}/docs/manual">
- <fileset dir="${spec.dist.manual}">
- </fileset>
- </copy>
- <copy todir="${spec.pear.dir}/docs/manual">
- <fileset dir="${spec.dist.manual}">
- </fileset>
- </copy>
- </target>
-
-</project>
View
22 examples/temp/library/TemperatureSampler.php
@@ -1,22 +0,0 @@
-<?php
-
-class TemperatureSampler
-{
-
- public $sensor = null;
-
- public function __construct($sensor)
- {
- $this->sensor = $sensor;
- }
-
- public function getAverageTemperature()
- {
- $total = 0;
- for ($i = 3; $i > 0; $i--) {
- $total += $this->sensor->readTemperature();
- }
- return $total / 3;
- }
-
-}
View
23 examples/temp/tests/TemperatureSamplerTest.php
@@ -1,23 +0,0 @@
-<?php
-
-require_once '../../../library/Mockery/Framework.php';
-require_once '../library/TemperatureSampler.php';
-
-class TemperatureSamplerTest extends PHPUnit_Framework_TestCase
-{
-
- public function testSensorCanAverageThreeTemperatureReadings()
- {
- $sensor = Mockery::mock('TemperatureSensor');
- $sensor->shouldReceive('readTemperature')->times(3)->andReturn(10, 12, 14);
- $sampler = new TemperatureSampler($sensor);
- $this->assertEquals(12, $sampler->getAverageTemperature());
- }
-
-}
-
-class TemperatureSensor {
-
-public function readTemperature(){}
-
-}
View
222 library/Mockery.php
@@ -1,222 +0,0 @@
-<?php
-
-class Mockery
-{
-
- protected static $_mockedObjects = array();
-
- protected $_className = '';
-
- protected $_mockClassName = null;
-
- protected $_runkit = false;
-
- public function __construct($className, $customName = null)
- {
- $this->_className = $className;
- if (!is_null($customName)) {
- $this->setMockClassName($customName);
- }
- }
-
- public static function mock($className, $custom = null, array $ctorArguments = array())
- {
- if (is_array($custom) && !class_exists($className)) {
- $mockery = new self($className);
- $mockery->createStubObject();
- } else {
- if (is_array($custom)) {
- $mockery = new self($className, null);
- } else {
- $mockery = new self($className, $custom);
- }
- $mockery->createMockObject();
- }
- if ($mockery->getMockClassName() === null) {
- $class = $mockery->getClassName();
- } else {
- $class = $mockery->getMockClassName();
- }
- if (count($ctorArguments) > 0)
- {
- $refMockObject = new ReflectionClass($class);
- $ctorArguments = self::_orderArguments($ctorArguments, $refMockObject);
- $mockObject = $refMockObject->newInstanceArgs($ctorArguments);
- }
- else
- {
- $mockObject = new $class();
- }
- if ($mockObject instanceof Mockery_Stub && is_array($custom)) {
- $mockObject->mockery_set($custom);
- } elseif (is_array($custom)) {
- foreach ($custom as $method => $return) {
- $mockObject->shouldReceive($method)
- ->withAnyArgs()
- ->zeroOrMoreTimes()
- ->andReturn($return);
- }
- }
- if (!$mockObject instanceof Mockery_Stub) {
- self::$_mockedObjects[] = $mockObject;
- }
-
- return $mockObject;
- }
-
- public static function verify()
- {
- $verified = true;
- foreach (self::$_mockedObjects as $mockObject) {
- if ($mockObject->mockery_verify() === false) {
- $verified = false;
- break;
- }
- }
- self::$_mockedObjects = array();
- return $verified;
- }
-
- public function getClassName()
- {
- return $this->_className;
- }
-
- public function setMockClassName($name = null)
- {
- if ($name === null) {
- $this->_mockClassName = uniqid('Mockery_');
- } else {
- $this->_mockClassName = $name;
- }
- }
-
- public function getMockClassName()
- {
- return $this->_mockClassName;
- }
-
- public function createMockObject(array $ctorArguments = array())
- {
- if (!class_exists($this->getClassName(), true) && !interface_exists($this->getClassName(), true)) {
- $this->setMockClassName($this->getClassName());
- }
- if ($this->getClassName() == $this->getMockClassName()) {
- $definition = $this->_createClassDefinition($this->getClassName());
- eval($definition);
- } else {
- $reflectedClass = new ReflectionClass($this->getClassName());
- if ($this->getMockClassName() === null) {
- $this->setMockClassName();
- }
- $definition = $this->_createReflectedDefinition($reflectedClass);
- eval($definition);
- }
- }
-
- public function createStubObject()
- {
- $definition = $this->_createStubDefinition();
- eval($definition);
- }
-
- protected function _createStubDefinition()
- {
- $definition = '';
- $definition .= 'class ' . $this->getClassName() . ' extends Mockery_Stub {';
- $definition .= '}';
- return $definition;
- }
-
- protected function _createReflectedDefinition(ReflectionClass $reflectedClass)
- {
- $inheritance = '';
- $definition = '';
- if ($reflectedClass->isFinal()) {
- throw new Mockery_Exception('Unable to create a Test Double for a class marked final');
- }
- if ($reflectedClass->isInterface()) {
- $inheritance = ' implements ' . $this->getClassName();
- } else {
- $inheritance = ' extends ' . $this->getClassName();
- }
- $definition .= 'class ' . $this->getMockClassName() . $inheritance . '{';
- $definition .= Mockery_Mockery::applyTo($reflectedClass);
- $definition .= '}';
- return $definition;
- }
-
- protected function _createClassDefinition($class)
- {
- $definition = '';
- $definition .= 'class ' . $class . '{';
- $definition .= Mockery_Mockery::applyTo($class);
- $definition .= '}';
- return $definition;
- }
-
- protected function _getImplementedMethodsDefinition(ReflectionClass $reflectedClass)
- {
- $definition = '';
- $methods = $reflectedClass->getMethods();
- foreach ($methods as $method) {
- if ($method->isAbstract()) {
- $definition .= $this->_createMethodPrototypeDefinition($method);
- $definition .= '{';
- $definition .= '}';
- }
- }
- return $definition;
- }
-
- protected function _createMethodPrototypeDefinition(ReflectionMethod $method)
- {
- $definition = '';
- $methodParams = array();
- $params = $method->getParameters();
- foreach ($params as $param) {
- $paramDef = '';
- if ($param->isArray()) {
- $paramDef .= 'array ';
- } elseif ($param->getClass()) {
- $paramDef .= $param->getClass()->getName() . ' ';
- }
- $paramDef .= '$' . $param->getName();
- if ($param->isOptional()) {
- $paramDef .= ' = ';
- if ($param->isDefaultValueAvailable()) {
- $paramDef .= var_export($param->getDefaultValue(), true);
- }
- }
- $methodParams[] = $paramDef;
- }
- $paramDef = implode(',', $methodParams);
- $modifiers = Reflection::getModifierNames($method->getModifiers());
- $access = str_replace('abstract ', '', implode(' ', $modifiers));
- $definition .= $access . ' function ' . $method->getName();
- $definition .= ' (' . $paramDef . ')';
- return $definition;
- }
-
- protected static function _orderArguments(array $ctorArguments, ReflectionClass $refMockObject)
- {
- $refArguments = $refMockObject->getConstructor()->getParameters();
- $orderedArgumentList = array();
- foreach($refArguments as $argument)
- {
- if (isset($ctorArguments[$argument->getName()]))
- {
- $orderedArgumentList[] = $ctorArguments[$argument->getName()];
- }
- else if ($argument->isOptional())
- {
- $orderedArgumentList[] = $argument->getDefaultValue();
- }
- else
- {
- throw new Mockery_Exception('Mandatory argumenet ' . $argument->getName() . ' not specified');
- }
- }
- return $orderedArgumentList;
- }
-}
View
23 library/Mockery/AtLeastCounter.php
@@ -1,23 +0,0 @@
-<?php
-
-class Mockery_AtLeastCounter
-{
-
- protected $_times = 1;
-
- public function __construct($times)
- {
- $this->_times = $times;
- }
-
- public function verify($callTimesActual)
- {
- return $callTimesActual >= $this->_times;
- }
-
- public function getDescription()
- {
- return 'at least ' . $this->_times . ($this->_times !== 1 ? ' times' : ' time');;
- }
-
-}
View
23 library/Mockery/AtMostCounter.php
@@ -1,23 +0,0 @@
-<?php
-
-class Mockery_AtMostCounter
-{
-
- protected $_times = 1;
-
- public function __construct($times)
- {
- $this->_times = $times;
- }
-
- public function verify($callTimesActual)
- {
- return $callTimesActual <= $this->_times;
- }
-
- public function getDescription()
- {
- return 'at most ' . $this->_times . ($this->_times !== 1 ? ' times' : ' time');
- }
-
-}
View
52 library/Mockery/Director.php
@@ -1,52 +0,0 @@
-<?php
-
-class Mockery_Director
-{
-
- protected $_methodName = null;
-
- protected $_expectations = array();
-
- public function __construct($methodName)
- {
- $this->_methodName = $methodName;
- }
-
- public function addExpectation(Mockery_Expectation $expectation)
- {
- $this->_expectations[] = $expectation;
- }
-
- public function verify()
- {
- foreach ($this->_expectations as $expectation) {
- $expectation->verify();
- }
- }
-
- public function call(array $args, $mock)
- {
- $expectation = $this->findExpectation($args);
- if (!empty($expectation)) {
- if ($expectation->isOrdered()) {
- $mock->mockery_incrementOrderedNumber();
- }
- $return = $expectation->verifyCall($args);
- return $return;
- } else {
- throw new Mockery_ExpectationException('unable to find a matching expectation for '
- . $this->_methodName . ' indicating this argument list was not expected: '
- . var_export($args, true));
- }
- }
-
- public function findExpectation(array $args)
- {
- foreach ($this->_expectations as $expectation) {
- if ($expectation->matchArgs($args)) {
- return $expectation;
- }
- }
- }
-
-}
View
6 library/Mockery/Exception.php
@@ -1,6 +0,0 @@
-<?php
-
-class Mockery_Exception extends Exception
-{
-
-}
View
239 library/Mockery/Expectation.php
@@ -1,239 +0,0 @@
-<?php
-
-class Mockery_Expectation
-{
-
- protected $_methodName = null;
-
- protected $_mockObject = null;
-
- protected $_expectedCallCount = null;
-
- protected $_actualCallCount = 0;
-
- protected $_expectedArgs = array();
-
- protected $_returnQueue = array();
-
- protected $_counterClass = 'Mockery_StandardCounter';
-
- protected $_orderedNumber = null;
-
- protected $_exceptionToThrow = null;
-
- protected $_regexArgs = false;
-
- protected $_counterRange = false;
-
- public function __construct($methodName, $mockObject)
- {
- $this->_methodName = $methodName;
- $this->_mockObject = $mockObject;
- $this->_expectedCallCount = new $this->_counterClass(1);
- }
-
- public function verify()
- {
- if (is_array($this->_expectedCallCount)) {
- $descriptions = array();
- foreach ($this->_expectedCallCount as $expectedCallCount) {
- $descriptions[] = $expectedCallCount->getDescription();
- }
- foreach ($this->_expectedCallCount as $expectedCallCount) {
- $this->_verifyCallCount($expectedCallCount, implode(' and ', $descriptions));
- }
- } else {
- $this->_verifyCallCount($this->_expectedCallCount, $this->_expectedCallCount->getDescription());
- }
- }
-
- protected function _verifyCallCount($expectedCallCount, $description)
- {
- if (!$expectedCallCount->verify($this->_actualCallCount)) {
- $this->_mockObject->mockery_setVerifiedStatus(false);
- throw new Mockery_ExpectationException(
- 'method ' . $this->_methodName
- .' called incorrect number of times; expected call ' . $description
- . ' but received ' . $this->_actualCallCount
- );
- }
- }
-
- public function times($times)
- {
- $times = intval($times);
- if ($this->_counterRange === true) {
- if (!is_array($this->_expectedCallCount)) {
- $this->_expectedCallCount = array();
- }
- $this->_expectedCallCount[] = new $this->_counterClass($times);
- } else {
- $this->_expectedCallCount = new $this->_counterClass($times);
- }
- return $this;
- }
-
- public function once()
- {
- return $this->times(1);
- }
-
- public function twice()
- {
- return $this->times(2);
- }
-
- public function never()
- {
- return $this->times(0);
- }
-
- public function zeroOrMoreTimes()
- {
- $this->_expectedCallCount = new Mockery_ZeroOrMoreCounter();
- return $this;
- }
-
- public function atLeast()
- {
- $this->_counterRange = true;
- $this->_counterClass = 'Mockery_AtLeastCounter';
- return $this;
- }
-
- public function atMost()
- {
- $this->_counterRange = true;
- $this->_counterClass = 'Mockery_AtMostCounter';
- return $this;
- }
-
- public function andReturn()
- {
- $args = func_get_args();
- foreach ($args as $arg) {
- $this->_returnQueue[] = $arg;
- }
- return $this;
- }
-
- public function andThrow($exceptionClass, $message = null)
- {
- if ($exceptionClass !== 'Exception') {
- $reflectedClass = new ReflectionClass($exceptionClass);
- if (!$reflectedClass->isSubclassOf( new ReflectionClass('Exception') )) {
- throw new Mockery_Exception(
- 'andThrow received value "' . $exceptionClass . '" which is not a'
- . ' class of type "Exception"'
- );
- }
- }
- if (!is_null($message)) {
- $this->_exceptionToThrow = array($exceptionClass, $message);
- } else {
- $this->_exceptionToThrow = $exceptionClass;
- }
- return $this;
- }
-
- public function with()
- {
- $args = func_get_args();
- $this->_expectedArgs = $args;
- return $this;
- }
-
- public function withAnyArgs()
- {
- $this->_expectedArgs = true;
- return $this;
- }
-
- public function withNoArgs()
- {
- $this->_expectedArgs = false;
- return $this;
- }
-
- public function withArgsMatching()
- {
- $args = func_get_args();
- $this->_expectedArgs = $args;
- $this->_regexArgs = true;
- return $this;
- }
-
- public function matchArgs(array $args)
- {
- if (empty($args) && empty($this->_expectedArgs) && is_array($this->_expectedArgs)) {
- return true;
- } elseif ($args == $this->_expectedArgs) {
- return true;
- } elseif ($this->_expectedArgs === true) {
- return true;
- } elseif ($this->_expectedArgs === false && empty($args)) {
- return true;
- } elseif ($this->_regexArgs === true && count($args) == count($this->_expectedArgs)) {
- $i = count($args);
- for ($j = 0; $j < $i; $j++) {
- if (is_array($args[$j]) || is_object($args[$j])
- || !preg_match($this->_expectedArgs[$j], $args[$j])) {
- return false;
- }
- return true;
- }
- }
- return false;
- }
-
- public function ordered()
- {
- $this->_orderedNumber = $this->_mockObject->mockery_getOrderedNumberNext();
- return $this;
- }
-
- public function isOrdered()
- {
- return !is_null($this->_orderedNumber);
- }
-
- public function verifyCall(array $args)
- {
- $this->_validateOrder();
- $this->_actualCallCount++;
- if (!is_null($this->_exceptionToThrow)) {
- if (is_array($this->_exceptionToThrow)) {
- $class = $this->_exceptionToThrow[0];
- $message = $this->_exceptionToThrow[1];
- throw new $class($message);
- } else {
- throw new $this->_exceptionToThrow;
- }
- }
- return $this->_returnValue();
- }
-
- protected function _validateOrder()
- {
- if ($this->isOrdered()) {
- $currentOrder = $this->_mockObject->mockery_getOrderedNumber();
- if ($currentOrder !== $this->_orderedNumber) {
- throw new Mockery_ExpectationException(
- 'Method ' . $this->_methodName . ' called out of order; expected at index of '
- . $this->_orderedNumber . ' but was called at ' . $currentOrder
- );
- }
- }
- }
-
- protected function _returnValue()
- {
- if (count($this->_returnQueue) == 1) {
- return $this->_returnQueue[0];
- }
- if (count($this->_returnQueue) > 1) {
- return array_shift($this->_returnQueue);
- }
- }
-
-}
View
6 library/Mockery/ExpectationException.php
@@ -1,6 +0,0 @@
-<?php
-
-class Mockery_ExpectationException extends Mockery_Exception
-{
-
-}
View
26 library/Mockery/Framework.php
@@ -1,26 +0,0 @@
-<?php
-
-class Mockery_Framework
-{
- public static function autoload($class)
- {
- if (substr($class, 0, 8) !== 'Mockery_' && $class !== 'Mockery') {
- return false;
- }
- $path = dirname(dirname(__FILE__));
- include $path . '/' . str_replace('_', '/', $class) . '.php';
- }
-
-}
-
-spl_autoload_register(array('Mockery_Framework', 'autoload'));
-
-function mockery($className, $custom = null, array $ctorArguments = array())
-{
- return Mockery::mock($className, $custom, $ctorArguments);
-}
-
-function mockery_verify()
-{
- return Mockery::verify();
-}
View
138 library/Mockery/Loader.php
@@ -0,0 +1,138 @@
+<?php
+/**
+ * SplClassLoader implementation that implements the technical interoperability
+ * standards for PHP 5.3 namespaces and class names.
+ *
+ * http://groups.google.com/group/php-standards/web/final-proposal
+ *
+ * // Example which loads classes for the Doctrine Common package in the
+ * // Doctrine\Common namespace.
+ * $classLoader = new SplClassLoader('Doctrine\Common', '/path/to/doctrine');
+ * $classLoader->register();
+ *
+ * @author Jonathan H. Wage <jonwage@gmail.com>
+ * @author Roman S. Borschel <roman@code-factory.org>
+ * @author Matthew Weier O'Phinney <matthew@zend.com>
+ * @author Kris Wallsmith <kris.wallsmith@gmail.com>
+ * @author Fabien Potencier <fabien.potencier@symfony-project.org>
+ */
+
+namespace Mockery;
+
+class Loader
+{
+ private $_fileExtension = '.php';
+ private $_namespace;
+ private $_includePath;
+ private $_namespaceSeparator = '\\';
+
+ /**
+ * Creates a new <tt>Loader</tt> that loads classes of the
+ * specified namespace.
+ *
+ * @param string $ns The namespace to use.
+ */
+ public function __construct($ns = 'Mockery', $includePath = null)
+ {
+ $this->_namespace = $ns;
+ $this->_includePath = $includePath;
+ }
+
+ /**
+ * Sets the namespace separator used by classes in the namespace of this class loader.
+ *
+ * @param string $sep The separator to use.
+ */
+ public function setNamespaceSeparator($sep)
+ {
+ $this->_namespaceSeparator = $sep;
+ }
+
+ /**
+ * Gets the namespace seperator used by classes in the namespace of this class loader.
+ *
+ * @return void
+ */
+ public function getNamespaceSeparator()
+ {
+ return $this->_namespaceSeparator;
+ }
+
+ /**
+ * Sets the base include path for all class files in the namespace of this class loader.
+ *
+ * @param string $includePath
+ */
+ public function setIncludePath($includePath)
+ {
+ $this->_includePath = $includePath;
+ }
+
+ /**
+ * Gets the base include path for all class files in the namespace of this class loader.
+ *
+ * @return string $includePath
+ */
+ public function getIncludePath()
+ {
+ return $this->_includePath;
+ }
+
+ /**
+ * Sets the file extension of class files in the namespace of this class loader.
+ *
+ * @param string $fileExtension
+ */
+ public function setFileExtension($fileExtension)
+ {
+ $this->_fileExtension = $fileExtension;
+ }
+
+ /**
+ * Gets the file extension of class files in the namespace of this class loader.
+ *
+ * @return string $fileExtension
+ */
+ public function getFileExtension()
+ {
+ return $this->_fileExtension;
+ }
+
+ /**
+ * Installs this class loader on the SPL autoload stack.
+ */
+ public function register()
+ {
+ spl_autoload_register(array($this, 'loadClass'));
+ }
+
+ /**
+ * Uninstalls this class loader from the SPL autoloader stack.
+ */
+ public function unregister()
+ {
+ spl_autoload_unregister(array($this, 'loadClass'));
+ }
+
+ /**
+ * Loads the given class or interface.
+ *
+ * @param string $className The name of the class to load.
+ * @return void
+ */
+ public function loadClass($className)
+ {
+ if (null === $this->_namespace
+ || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) {
+ $fileName = '';
+ $namespace = '';
+ if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) {
+ $namespace = substr($className, 0, $lastNsPos);
+ $className = substr($className, $lastNsPos + 1);
+ $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
+ }
+ $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;
+ require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;
+ }
+ }
+}
View
93 library/Mockery/Mockery.php
@@ -1,93 +0,0 @@
-<?php
-
-class Mockery_Mockery {
-
- protected static $_added = array(
- 'shouldReceive',
- 'mockery_verify',
- 'mockery_setVerifiedStatus',
- 'mockery_getOrderedNumberNext',
- 'mockery_call',
- 'mockery_getOrderedNumber',
- 'mockery_incrementOrderedNumber'
- );
-
- protected static $_standardMethods = null;
-
- public static function applyTo($reflectedClass)
- {
- if (!is_object($reflectedClass)) {
- return self::_getStandardMethods() . self::_getOpenInterceptionMethod();
- }
- $mockeryDefinition = '';
- $methods = $reflectedClass->getMethods();
- foreach ($methods as $method) {
- if (!$method->isFinal() && !$method->isDestructor()
- && $method->getName() !== '__clone') {
- $mockeryDefinition .= self::_replaceMethod($method);
- }
- }
- $mockeryDefinition .= self::_getStandardMethods();
- return $mockeryDefinition;
- }
-
- protected static function _replaceMethod(ReflectionMethod $method)
- {
- $body = '';
- $mname = $method->getName();
- if ($mname !== '__construct' && $method->isPublic()) {
- $body = '$store = Mockery_Store::getInstance(spl_object_hash($this));'
- . '$directors = $store->directors;'
- . '$args = func_get_args();'
- . 'return $this->mockery_call("' . $mname . '", $args);';
- }
- $methodParams = array();
- $params = $method->getParameters();
- foreach ($params as $param) {
- $paramDef = '';
- if ($param->isArray()) {
- $paramDef .= 'array ';
- } elseif ($param->getClass()) {
- $paramDef .= $param->getClass()->getName() . ' ';
- }
- $paramDef .= '$' . $param->getName();
- if ($param->isOptional()) {
- $paramDef .= ' = ';
- if ($param->isDefaultValueAvailable()) {
- $paramDef .= var_export($param->getDefaultValue(), true);
- }
- }
- $methodParams[] = $paramDef;
- }
- $paramDef = implode(',', $methodParams);
- if ($method->isPublic()) {
- $access = 'public';
- } elseif($method->isProtected()) {
- $access = 'protected';
- } else {
- $access = 'private';
- }
- if ($method->isStatic()) {
- $access .= ' static';
- }
- return $access . ' function ' . $mname . '(' . $paramDef . ')'
- . '{' . $body . '}';
- }
-
- protected static function _getOpenInterceptionMethod()
- {
- $def = 'public function __call($method, $args) {'
- . '$this->mockery_call($method, $args);'
- . '}';
- return $def;
- }
-
- protected static function _getStandardMethods()
- {
- if (self::$_standardMethods === null) {
- self::$_standardMethods = file_get_contents(dirname(__FILE__).'/Templates/Methods');
- }
- return self::$_standardMethods;
- }
-
-}
View
26 library/Mockery/StandardCounter.php
@@ -1,26 +0,0 @@
-<?php
-
-class Mockery_StandardCounter
-{
-
- protected $_times = 1;
-
- public function __construct($times)
- {
- $this->_times = $times;
- }
-
- public function verify($callTimesActual)
- {
- if ($this->_times == $callTimesActual) {
- return true;
- }
- return false;
- }
-
- public function getDescription()
- {
- return $this->_times . ($this->_times !== 1 ? ' times' : ' time');
- }
-
-}
View
42 library/Mockery/Store.php
@@ -1,42 +0,0 @@
-<?php
-
-class Mockery_Store
-{
-
- protected static $_instances = array();
-
- protected $_data = array();
-
- public function __construct(array $data)
- {
- $this->_data = $data;
- }
-
- public static function getInstance($name)
- {
- if (!isset(self::$_instances[$name])) {
- self::$_instances[$name] = new self(array(
- 'directors' => array(),
- 'verified' => false,
- 'orderedNumber' => -1,
- 'orderedNumberNext' => -1
- ));
- }
- return self::$_instances[$name];
- }
-
- public function __set($name, $value)
- {
- if (isset($this->_data[$name])) {
- $this->_data[$name] = $value;
- }
- }
-
- public function __get($name)
- {
- if (isset($this->_data[$name])) {
- return $this->_data[$name];
- }
- }
-
-}
View
21 library/Mockery/Stub.php
@@ -1,21 +0,0 @@
-<?php
-
-class Mockery_Stub
-{
-
- protected $_mockery_data = array();
-
- public function __call($method, array $args)
- {
- if (isset($this->_mockery_data[$method])) {
- return $this->_mockery_data[$method];
- }
- throw new Mockery_Exception('Method called, ' . $method . ', has not been stubbed');
- }
-
- public function mockery_set(array $data)
- {
- $this->_mockery_data = $data;
- }
-
-}
View
67 library/Mockery/Templates/Methods
@@ -1,67 +0,0 @@
-public function shouldReceive($methodName)
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- $directors = $store->directors;
- if (!isset($directors[$methodName])) {
- $directors[$methodName] = new Mockery_Director($methodName);
- }
- $expectation = new Mockery_Expectation($methodName, $this);
- $directors[$methodName]->addExpectation($expectation);
- $store->directors = $directors;
- return $expectation;
-}
-
-public function mockery_verify()
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- if ($store->verified) {
- return $store->verified;
- }
- $store->verified = true;
- foreach ($store->directors as $director) {
- $director->verify();
- }
- return $store->verified;
-}
-
-public function mockery_setVerifiedStatus($bool)
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- $store->verified = $bool;
-}
-
-public function mockery_call($methodName, $args)
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- $return = null;
- $directors = $store->directors;
- if (!isset($directors[$methodName])) {
- $this->shouldReceive($methodName)->never();
- $directors = $store->directors;
- }
- $return = $directors[$methodName]->call($args, $this);
- return $return;
-}
-
-public function mockery_getOrderedNumberNext()
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- $orderedNumberNext = $store->orderedNumberNext;
- $orderedNumberNext++;
- $store->orderedNumberNext = $orderedNumberNext;
- return $orderedNumberNext;
-}
-
-public function mockery_getOrderedNumber()
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- return $store->orderedNumber;
-}
-
-public function mockery_incrementOrderedNumber()
-{
- $store = Mockery_Store::getInstance(spl_object_hash($this));
- $orderedNumber = $store->orderedNumber;
- $orderedNumber++;
- $store->orderedNumber = $orderedNumber;
-}
View
16 library/Mockery/ZeroOrMoreCounter.php
@@ -1,16 +0,0 @@
-<?php
-
-class Mockery_ZeroOrMoreCounter
-{
-
- public function verify($callTimesActual)
- {
- return true;
- }
-
- public function getDescription()
- {
- return 'zero or more times';
- }
-
-}
View
33 tests/AllTests.php
@@ -1,33 +0,0 @@
-<?php
-
-if (!defined('PHPUnit_MAIN_METHOD')) {
- define('PHPUnit_MAIN_METHOD', 'AllTests::main');
-}
-
-require_once 'MockeryTest.php';
-require_once 'MockeryExpectationsTest.php';
-require_once 'RegressionTest.php';
-require_once 'StubExpectationsTest.php';
-
-class AllTests
-{
- public static function main()
- {
- PHPUnit_TextUI_TestRunner::run(self::suite());
- }
-
- public static function suite()
- {
- $suite = new PHPUnit_Framework_TestSuite('Mockery: Cross Framework Mock Objects and Stubs for PHP5');
-
- $suite->addTestSuite('MockeryTest');
- $suite->addTestSuite('MockeryExpectationsTest');
- //$suite->addTestSuite('StubExpectationsTest');
-
- return $suite;
- }
-}
-
-if (PHPUnit_MAIN_METHOD == 'AllTests::main') {
- AllTests::main();
-}
View
77 tests/Bootstrap.php
@@ -0,0 +1,77 @@
+<?php
+/**
+ * Mockery
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://github.com/padraic/mockery/master/LICENSE
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to padraic@php.net so we can send you a copy immediately.
+ *
+ * @category Mockery
+ * @package Mockery
+ * @subpackage UnitTests
+ * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
+ * @license http://github.com/padraic/mutateme/master/LICENSE New BSD License
+ */
+
+/*
+ * Set error reporting to the level to which Mutateme code must comply.
+ */
+error_reporting(E_ALL | E_STRICT);
+
+/*
+ * Determine the root, library, and tests directories of the framework
+ * distribution.
+ */
+$root = realpath(dirname(dirname(__FILE__)));
+$library = "$root/library";
+$tests = "$root/tests";
+
+/*
+ * Prepend the Mutateme library/ and tests/ directories to the
+ * include_path. This allows the tests to run out of the box and helps prevent
+ * loading other copies of the code and tests that would supercede
+ * this copy.
+ */
+$path = array(
+ $library,
+ $tests,
+ get_include_path(),
+);
+set_include_path(implode(PATH_SEPARATOR, $path));
+
+if (defined('TESTS_GENERATE_REPORT') && TESTS_GENERATE_REPORT === true &&
+ version_compare(PHPUnit_Runner_Version::id(), '3.1.6', '>=')) {
+
+ /*
+ * Add Mutateme library/ directory to the PHPUnit code coverage
+ * whitelist. This has the effect that only production code source files
+ * appear in the code coverage report and that all production code source
+ * files, even those that are not covered by a test yet, are processed.
+ */
+ PHPUnit_Util_Filter::addDirectoryToWhitelist($library);
+
+ /*
+ * Omit from code coverage reports the contents of the tests directory
+ */
+ foreach (array('.php', '.phtml', '.csv', '.inc') as $suffix) {
+ PHPUnit_Util_Filter::addDirectoryToFilter($tests, $suffix);
+ }
+ PHPUnit_Util_Filter::addDirectoryToFilter(PEAR_INSTALL_DIR);
+ PHPUnit_Util_Filter::addDirectoryToFilter(PHP_LIBDIR);
+}
+
+require_once 'Mockery/Loader.php';
+$loader = new \Mockery\Loader;
+$loader->register();
+
+/*
+ * Unset global variables that are no longer needed.
+ */
+unset($root, $library, $tests, $path);
+
View
2  tests/Mockery/.gitignore
@@ -1,2 +0,0 @@
-*.php~
-*.phpt~
View
46 tests/Mockery/LoaderTest.php
@@ -0,0 +1,46 @@
+<?php
+/**
+ * Mockery
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://github.com/padraic/mutateme/master/LICENSE
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to padraic@php.net so we can send you a copy immediately.
+ *
+ * @category Mockery
+ * @package Mockery
+ * @subpackage UnitTests
+ * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
+ * @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
+ */
+
+class Mockery_LoaderTest extends PHPUnit_Framework_TestCase
+{
+
+ public function setUp()
+ {
+ spl_autoload_unregister('\Mockery\Loader::loadClass');
+ }
+
+ public function testCallingRegisterRegistersSelfAsSplAutoloaderFunction()
+ {
+ require_once 'Mockery/Loader.php';
+ $loader = new \Mockery\Loader;
+ $loader->register();
+ $expected = array($loader, 'loadClass');
+ $this->assertTrue(in_array($expected, spl_autoload_functions()));
+ }
+
+ public function tearDown()
+ {
+ spl_autoload_unregister('\Mockery\Loader::loadClass');
+ $loader = new \Mockery\Loader;
+ $loader->register();
+ }
+
+}
View
527 tests/MockeryExpectationsTest.php
@@ -1,527 +0,0 @@
-<?php
-
-// Test helper
-require_once dirname(__FILE__) . '/TestHelper.php';
-require_once dirname(dirname(__FILE__)) . '/library/Mockery/Framework.php';
-require_once dirname(__FILE__) . '/_files/Album.php';
-
-class MockeryExpectationsTest extends PHPUnit_Framework_TestCase
-{
-
- public function testShouldReturnTrueOnValidationByDefaultIfNoExpectationsSet()
- {
- $mock = mockery('MockeryTest_EmptyClass');
- try {
- $this->assertTrue($mock->mockery_verify());
- } catch (Exception $e) {
- $this->fail('Mock object checking threw an Exception reading: ' . $e->getMessage());
- }
- }
-
- public function testShouldThrowDefaultExceptionIfMethodCallCountIsUnexpected()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName');
- $mock->getName();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail('Expected exception was not thrown');
- } catch (Mockery_Exception $e) {
- }
- }
-
- public function testShouldExpectNumberOfMethodsInTimesTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->times(5);
- for ($i=0; $i <= 4; $i++) {
- $mock->getName();
- }
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldReturnSelfFromTimesTermInvocation()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->times(1);
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldSetReturnValueInTermsAndDefaultToReturningValueForAllCalls()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->andReturn('Joe');
- $mock->getName();
- $this->assertEquals('Joe', $mock->getName());
- }
-
- public function testShouldSetReturnValueButThrowDefaultExceptionIfMethodCallCountIsUnexpected()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->andReturn('Joe');
- $mock->getName();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail('Expected exception was not thrown');
- } catch (Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnValuesInOrderOfSettingButReturnLastValueRemainingOnOtherCalls()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->andReturn('Joe', 'Paddy', 'Travis');
- for ($i=0; $i <= 5; $i++) {
- $mock->getName();
- }
- $this->assertEquals('Travis', $mock->getName());
- }
-
- public function testShouldReturnSelfFromReturnTermInvocation()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->times(1)->andReturn('Joe');
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldSetExpectedArgUsingWithTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('setName')->with('Black Album');
- $mock->setName('Black Album');
- try {
- $mock->mockery_verify();
- } catch (Mockery_Exception $e) {
- $this->fail($e->getMessage());
- }
- }
-
- public function testShouldThrowExceptionIfExpectedParameterNotUsedFromWithTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('setName')->with('Black Album');
- try {
- $mock->setName('Black');
- $this->fail('Expected exception never materialised on unexpected parameter');
- } catch (Mockery_Exception $e) {
- }
- }
-
- // added tests
-
- public function testShouldSetExpectedMultipleArgsUsingWithTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('setTerms')->with('album', 'music');
- $mock->setTerms('album', 'music');
- try {
- $mock->mockery_verify();
- } catch (Mockery_Exception $e) {
- $this->fail($e->getMessage());
- }
- }
-
- public function testShouldSetExpectedMultipleArgsMatchingRegexUsingWithTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('setTerms')->withArgsMatching("/\d/", "/^php/");
- $mock->setTerms('2', 'php5');
- try {
- $mock->mockery_verify();
- } catch (Mockery_Exception $e) {
- $this->fail($e->getMessage());
- }
- }
-
- public function testShouldThrowExceptionOnArgsNotMatchingRegexUsingWithTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('setTerms')->withArgsMatching("/\d/", "/^php/");
- try {
- $mock->setTerms('A', 'php5');
- $this->fail();
- } catch (Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfFromWithTermInvocation()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('setName')->times(1)->with('Joe');
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldAllowNoCallsForZeroormoretimesTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->zeroOrMoreTimes();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldAllowOneCallWithOnceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->once();
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldThrowExceptionIfLessThanOnceUsingOnceTern()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->once();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldThrowExceptionIfGreaterThanOnceUsingOnceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->once();
- $mock->getName();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromOnceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->once();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldAllowTwoCallsWithTwiceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->twice();
- $mock->getName();
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldThrowExceptionIfLessThanTwiceUsingTwiceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->twice();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldThrowExceptionIfGreaterThanTwiceUsingTwiceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->once();
- $mock->getName();
- $mock->getName();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromTwiceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->twice();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldAllowNoCallsWithNeverTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->never();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldThrowExceptionIfAnyCallAfterNeverTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->never();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromNeverTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->never();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldAllowAnyCallsForZeroormoretimesTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->zeroOrMoreTimes();
- for ($i=0;$i<=4;$i++) {
- $mock->getName();
- }
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldAllowZeroCallsForZeroormoretimesTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->zeroOrMoreTimes();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldReturnSelfInstanceFromZeroormoretimesTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->zeroOrMoreTimes();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldSetTimesMinimumWithOnceUsingAtleastTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atLeast()->once();
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldSetTimesMinimumWithTimesUsingAtleastTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atLeast()->times(2);
- $mock->getName();
- $mock->getName();
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldThrowExceptionIfLessThanMinimumUsingAtleastTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atLeast()->twice();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromAtleastTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->atLeast();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldSetTimesMaximumWithOnceUsingAtmostTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atMost()->once();
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldSetTimesMaximumWithTimesUsingAtmostTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atMost()->times(2);
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldThrowExceptionIfMoreThanTwiceUsingTwiceTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->twice();
- $mock->getName();
- $mock->getName();
- $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromAtmostTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->atMost();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldSetTimesMinimumAndMaximumUsingLeastAndMostTerms()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atLeast()->once()->atMost()->times(3);
- $mock->getName();
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldThrowExceptionWhenMinimumCallCountRangeNotMet()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atLeast()->once()->atMost()->times(3);
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldThrowExceptionWhenMaximumCallCountRangeExceeded()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->atLeast()->once()->atMost()->times(3);
- $mock->getName(); $mock->getName();
- $mock->getName(); $mock->getName();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- public function testShouldAllowAnyArgsUsingWithanyargsTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->withAnyArgs()->andReturn('SomeName');
- $this->assertEquals('SomeName', $mock->getName('x', 'y', 'z'));
- }
-
- public function testShouldReturnSelfInstanceFromWithanyargsTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->withAnyArgs();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldDisallowArgsUsingWithnoargsTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->withNoArgs();
- try {
- $mock->getName('x');
- $this->fail();
- } catch (Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromWithnoargsTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->withNoArgs();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldReturnSelfInstanceFromWithargsmatchingTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->withArgsMatching();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldObeyOrderingViaSequenceOfOrderedTermCalls()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('setName')->with('name')->ordered();
- $mock->shouldReceive('getName')->ordered();
- $mock->setName('name');
- $mock->getName();
- $this->assertTrue($mock->mockery_verify());
- }
-
- public function testShouldDisallowMethodCallingIfMethodHasSpecifiedOrder()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->withNoArgs()->ordered();
- $mock->shouldReceive('setName')->once()->withAnyArgs()->ordered();
- try {
- $mock->setName('x');
- $this->fail();
- } catch (Mockery_Exception $e) {
- }
- }
-
- public function testShouldAllowMethodCallingOfUnorderedExpectationsInAnyOrder()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('getName')->withNoArgs()->ordered();
- $mock->shouldReceive('setName')->once()->withAnyArgs()->ordered();
- $mock->shouldReceive('hasName')->withNoArgs(); // not ordered; call any time
- try {
- $mock->hasName();
- $mock->getName();
- $mock->setName('x');
- } catch (Mockery_Exception $e) {
- $this->fail();
- }
- }
-
- public function testShouldReturnSelfInstanceFromOrderedTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->ordered();
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
- public function testShouldThrowSpecifiedExceptionUsingAndthrowTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('hasName')->andThrow('MockeryTest_Album_Exception');
- try {
- $mock->hasName();
- $this->fail();
- } catch (MockeryTest_Album_Exception $e) {
- // pass
- } catch (Exception $e) {
- $this->fail();
- }
- }
-
- public function testShouldThrowSpecifiedExceptionWithMessageUsingAndthrowTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $mock->shouldReceive('hasName')->andThrow('MockeryTest_Album_Exception', 'somemessage');
- try {
- $mock->hasName();
- $this->fail();
- } catch (MockeryTest_Album_Exception $e) {
- $this->assertEquals('somemessage', $e->getMessage());
- }
- }
-
- public function testShouldThrowExceptionIfClassPassedToAndthrowTermNotAnException()
- {
- $mock = mockery('MockeryTest_Album');
- try {
- $mock->shouldReceive('hasName')->andThrow('MockeryTest_Album');
- $this->fail();
- } catch (Mockery_Exception $e) {
- }
- }
-
- public function testShouldReturnSelfInstanceFromAndthrowTerm()
- {
- $mock = mockery('MockeryTest_Album');
- $object = $mock->shouldReceive('getName')->andThrow('Exception');
- $this->assertTrue($object instanceof Mockery_Expectation);
- }
-
-}
View
124 tests/MockeryTest.php
@@ -1,124 +0,0 @@
-<?php
-
-// Test helper
-require_once dirname(__FILE__) . '/TestHelper.php';
-require_once dirname(dirname(__FILE__)) . '/library/Mockery/Framework.php';
-require_once dirname(__FILE__) . '/_files/Album.php';
-
-class MockeryTest extends PHPUnit_Framework_TestCase
-{
-
- // Basic Mocking Of Existing Classes
-
- public function testShouldCreateMockInheritingClassTypeFromOriginal()
- {
- $mock = mockery('MockeryTest_EmptyClass');
- $this->assertTrue($mock instanceof MockeryTest_EmptyClass);
- }
-
- public function testShouldCreateMockInheritingTypeIfOriginalAnInterface()
- {
- $mock = mockery('MockeryTest_Interface');
- $this->assertTrue($mock instanceof MockeryTest_Interface);
- }
-
- public function testShouldCreateMockWhereAnyInterfaceMethodsAreImplemented()
- {
- $mock = mockery('MockeryTest_InterfaceWithAbstractMethod');
- $this->assertTrue($mock instanceof MockeryTest_InterfaceWithAbstractMethod);
- }
-
- public function testShouldCreateMockWhereAnyAbstractMethodsAreImplemented()
- {
- $mock = mockery('MockeryTest_AbstractWithAbstractMethod');
- $this->assertTrue($mock instanceof MockeryTest_AbstractWithAbstractMethod);
- }
-
- public function testShouldImplementAbstractMethodsWithFullParameterList()
- {
- $mock = mockery('MockeryTest_InterfaceWithAbstractMethodAndParameters');
- $this->assertTrue($mock instanceof MockeryTest_InterfaceWithAbstractMethodAndParameters);
- }
-
- public function testShouldCreateMockUsingCustomNameIfSupplied()
- {
- $mock = mockery('MockeryTest_EmptyClass', 'MockeryTest_CustomNamed');
- $this->assertTrue($mock instanceof MockeryTest_CustomNamed);
- }
-
- // Stubbing of Existing Classes
-
- public function testShouldCreateStubInheritingClassTypeFromOriginal()
- {
- $mock = mockery('MockeryTest_SimpleClass', array('get' => 'foo'));
- $this->assertEquals('foo', $mock->get());
- }
-
- // Stubbing Of Non-existing Classes
-
- public function testShouldCreateNewClassWithGivenNameIfNotYetExisting()
- {
- $mock = mockery('MockeryTest_DoesntExist');
- $this->assertTrue($mock instanceof MockeryTest_DoesntExist);
- }
-
- public function testShouldWithoutMethodHashCreateAMockObject()
- {
- $mock = mockery('MockeryTest_DoesntExist3');
- $this->assertTrue($mock->shouldReceive('doSomething') instanceof Mockery_Expectation);
- }
-
- public function testShouldCreateStubFromAnArrayOfMethodsAndReturnValues()
- {
- $mock = mockery('MockeryTest_DoesntExist2', array('get' => 'foo'));
- $this->assertEquals('foo', $mock->get());
- }
-
- // Untouched classes
-
- public function testShouldLeaveMethodsUntouchedUnlessExpectationsWereCreated()
- {
- mockery('MockeryTest_SimpleClass');
- $nonMock = new MockeryTest_SimpleClass;
- $this->assertEquals('simple', $nonMock->get());
- }
-
- // Touched classes
-
- public function testShouldNotLeaveMethodsUntouchedIfExpectationsWereCreated()
- {
- $mock = mockery('MockeryTest_SimpleClass');
- $mock->shouldReceive('set')->once();
- $mock->get();
- $mock->set();
- try {
- $mock->mockery_verify();
- $this->fail();
- } catch(Mockery_Exception $e) {
- }
- }
-
- // Test duplicate mocks avoided
- public function testDoubleMockingSameClassOccursWithoutError()
- {
- $mock = mockery('MockeryTest_EmptyClass');
- $mock2 = mockery('MockeryTest_EmptyClass');
- $this->assertTrue($mock !== $mock2);
- }
-
- // Added extra parameter to pass optional constructor arguments
- public function testShouldBeAbleToMockNonDefaultConstructorClass()
- {
- // Arguments are deliberately given in inverse order
- $arguments = array(
- 'founded' => new DateTime('now'),
- 'name' => 'HeavyMetalInc.'
- );
- $mock = mockery('MockeryTest_RecordLabel', null, $arguments);
- $this->assertTrue($mock instanceof MockeryTest_RecordLabel);
- $mock = mockery('MockeryTest_RecordLabel', 'MockertyTest_TestRecordLabel', $arguments);
- $this->assertTrue($mock instanceof MockeryTest_RecordLabel);
- }
-
-
-}
View
32 tests/RegressionTest.php
@@ -1,32 +0,0 @@
-<?php
-
-// Test helper
-require_once dirname(__FILE__) . '/TestHelper.php';
-require_once dirname(dirname(__FILE__)) . '/library/Mockery/Framework.php';