### Install Mockery with Composer update Source: https://docs.mockery.io/en/latest/_sources/getting_started/installation.rst.txt Runs Composer update to install dependencies defined in composer.json. Mockery is installed as a development dependency and will not be installed with --no-dev. ```bash php composer.phar update ``` -------------------------------- ### Mock expectation example Source: https://docs.mockery.io/en/latest/_sources/reference/spies.rst.txt Shows the Arrange-Expect-Act-Assert style with a mock, where expectations are set before acting on the SUT. ```php // arrange $mock = \Mockery::mock('MyDependency'); $sut = new MyClass($mock); // expect $mock->shouldReceive('foo') ->once() ->with('bar'); // act $sut->callFoo(); // assert \Mockery::close(); ``` -------------------------------- ### Create a mock with interfaces as second argument Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates a mock of 'MyClass' that implements the interfaces listed in the second argument. Equivalent to the previous example. ```php $mock = \Mockery::mock('MyClass', 'MyInterface, OtherInterface'); ``` -------------------------------- ### Fetcher and MyClass with non-static fetch() Source: https://docs.mockery.io/en/latest/cookbook/class_constants.html Alternative version of the example classes where fetch() is an instance method and MyClass receives the fetcher as a parameter. ```php class Fetcher { const SUCCESS = 0; const FAILURE = 1; public function fetch() { // Fetcher gets something for us from somewhere... return self::SUCCESS; } } class MyClass { public function doFetching($fetcher) { $response = $fetcher->fetch(); if ($response == Fetcher::SUCCESS) { echo "Thanks!" . PHP_EOL; } else { echo "Try again!" . PHP_EOL; } } } ``` -------------------------------- ### Fetcher class with constants for constants map example Source: https://docs.mockery.io/en/latest/cookbook/class_constants.html Class with constants used to demonstrate the constants map configuration. ```php class Fetcher { const SUCCESS = 0; const FAILURE = 1; public function fetch() { // Fetcher gets something for us from somewhere... return self::SUCCESS; } } ``` -------------------------------- ### withSomeOfArgs example with integer arguments Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt This example shows using withSomeOfArgs to match calls that include the given arguments, regardless of order. Type must match. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->withSomeOfArgs(1, 2); ``` -------------------------------- ### Install Mockery via Composer require command Source: https://docs.mockery.io/en/latest/_sources/getting_started/installation.rst.txt Directly adds Mockery as a development dependency from the command line. ```bash php composer.phar require --dev mockery/mockery ``` -------------------------------- ### Spy usage example Source: https://docs.mockery.io/en/latest/_sources/reference/spies.rst.txt Shows the Arrange-Act-Assert style with a spy, where assertions are made after acting on the SUT. ```php // arrange $spy = \Mockery::spy('MyDependency'); $sut = new MyClass($spy); // act $sut->callFoo(); // assert $spy->shouldHaveReceived() ->foo() ->with('bar'); ``` -------------------------------- ### Instance Mocking Example: new \MyNamespace\Foo Source: https://docs.mockery.io/en/latest/reference/instance_mocking.html Shows the statement that triggers instance mocking, replacing the real class with a mock object. The alias imports expectations from the original mock, which is never verified and should be ignored after setup. This works when autoloading is the primary class loading mechanism; a require statement can still include the real class and cause a fatal error. ```php $obj = new \MyNamespace\Foo; ``` -------------------------------- ### Service class with hard dependency Source: https://docs.mockery.io/en/latest/cookbook/mocking_hard_dependencies.html Example class that instantiates an external service using the 'new' keyword, which is a hard dependency that needs to be mocked. ```php sendSomething($param); return $externalService->getSomething(); } } ``` -------------------------------- ### Using namedMock() with a stub class for non-static fetch() Source: https://docs.mockery.io/en/latest/cookbook/class_constants.html Test setup for the non-static version. Creates a mock named Fetcher based on FetcherStub and passes it to MyClass::doFetching(). ```php class FetcherStub { const SUCCESS = 0; const FAILURE = 1; } $mock = \Mockery::mock('Fetcher', 'FetcherStub') $mock->shouldReceive('fetch') ->andReturn(0); $myClass = new MyClass(); $myClass->doFetching($mock); ``` -------------------------------- ### Mock vs Spy example Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Illustrates the difference between a mock and a spy. A mock requires setting expectations before the call, while a spy verifies calls after the fact. The return value of a spy method call is always null. ```php $mock = \Mockery::mock('MyClass'); $spy = \Mockery::spy('MyClass'); $mock->shouldReceive('foo')->andReturn(42); $mockResult = $mock->foo(); $spyResult = $spy->foo(); $spy->shouldHaveReceived()->foo(); var_dump($mockResult); // int(42) var_dump($spyResult); // null ``` -------------------------------- ### hasKey() matcher example Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is an array containing the given key name. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::hasKey(key)); ``` -------------------------------- ### Closure argument matching example with even numbers Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt This example shows a closure that matches even arguments. Calls with even numbers match, odd numbers throw NoMatchingExpectationException. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo')->withArgs(function ($arg) { if ($arg % 2 == 0) { return true; } return false; }); $mock->foo(4); // matches the expectation $mock->foo(3); // throws a NoMatchingExpectationException ``` -------------------------------- ### Instance Mocking: new statement example Source: https://docs.mockery.io/en/latest/_sources/reference/instance_mocking.rst.txt Shows a typical instantiation statement that instance mocking will intercept, replacing the real class with a mock object. ```php $obj = new \MyNamespace\Foo; ``` -------------------------------- ### Set up ordered database query expectations with Mockery Source: https://docs.mockery.io/en/latest/_sources/getting_started/quick_reference.rst.txt Use this snippet to define a sequence of expected method calls on a mock object. The 'ordered' method enforces call order, and the 'queries' group allows multiple calls to be ordered together. The example shows how to use 'with' to match arguments and 'andReturn' to specify return values. ```php class DbTest extends MockeryTestCase { public function testOrderedQueries() { $db = \Mockery::mock('db'); $db->shouldReceive('startup')->once()->ordered(); $db->shouldReceive('query')->with('CPWR')->andReturn(12.3)->once()->ordered('queries'); $db->shouldReceive('query')->with('MSFT')->andReturn(10.0)->once()->ordered('queries'); $db->shouldReceive('query')->with(\Mockery::pattern("/^....$/"))->andReturn(3.3)->atLeast()->once()->ordered('queries'); $db->shouldReceive('finish')->once()->ordered(); // ... test code here using the mock } } ``` -------------------------------- ### Example of BigParentClass and ChildClass Source: https://docs.mockery.io/en/latest/_sources/cookbook/big_parent_class.rst.txt Shows a legacy code structure where ChildClass extends BigParentClass and calls its doesEverything() method. This is the target for testing. ```php class BigParentClass { public function doesEverything() { // sets up database connections // writes to log files } } class ChildClass extends BigParentClass { public function doesOneThing() { // but calls on BigParentClass methods $result = $this->doesEverything(); // does something with $result return $result; } } ``` -------------------------------- ### Fetcher and MyClass classes with class constants Source: https://docs.mockery.io/en/latest/cookbook/class_constants.html Example classes used to illustrate the problem. Fetcher defines constants SUCCESS and FAILURE and a static fetch() method. MyClass calls Fetcher::fetch() and compares the result to Fetcher::SUCCESS. ```php class Fetcher { const SUCCESS = 0; const FAILURE = 1; public static function fetch() { // Fetcher gets something for us from somewhere... return self::SUCCESS; } } class MyClass { public function doFetching() { $response = Fetcher::fetch(); if ($response == Fetcher::SUCCESS) { echo "Thanks!" . PHP_EOL; } else { echo "Try again!" . PHP_EOL; } } } ``` -------------------------------- ### shouldReceive Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Declares that a mock object should receive a call to the specified method(s). This is the starting point for all expectations and constraints. ```APIDOC ## shouldReceive ### Description Declares that a mock object should receive a call to the specified method(s). This is the starting point for all expectations and constraints. ### Method shouldReceive ### Parameters - **methodNames** (string|array) - Required - The name(s) of the method(s) expected to be called. - **returnValues** (array) - Optional - An associative array mapping method names to return values. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method'); ``` ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method_1', 'name_of_method_2'); ``` ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive([ 'name_of_method_1' => 'return value 1', 'name_of_method_2' => 'return value 2', ]); ``` ### Response No return value specified. ``` -------------------------------- ### Using Mockery::anyOf() matcher Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that equals any one of the given parameters. The example shows \Mockery::anyOf(1, 2) and its Hamcrest equivalent anyOf(1,2). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::anyOf(1, 2)); // Hamcrest equivalent $mock->shouldReceive('foo') ->with(anyOf(1,2)); ``` -------------------------------- ### Multiple return values with andReturn() and call examples Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Shows the behavior of multiple return values: the first three calls return 1, 2, and 3, and any further calls return 3. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo')->andReturn(1, 2, 3); $mock->foo(); // int(1) $mock->foo(); // int(2) $mock->foo(); // int(3) $mock->foo(); // int(3) ``` -------------------------------- ### Return mock object with getMock() Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Returns the current mock object from an expectation chain. Useful for keeping mock setups as a single statement. ```php $mock = \Mockery::mock('foo')->shouldReceive('foo')->andReturn(1)->getMock(); ``` -------------------------------- ### Example of a Demeter chain method call Source: https://docs.mockery.io/en/latest/reference/demeter_chains.html Shows a typical fluent interface chain where multiple methods are called in sequence on an object. This is the pattern that Mockery's demeter chain mocking is designed to handle. ```php $object->foo()->bar()->zebra()->alpha()->selfDestruct(); ``` -------------------------------- ### PHP class Post with publishPost method Source: https://docs.mockery.io/en/latest/_sources/cookbook/mockery_on.rst.txt Defines a Post service class with a publishPost method that saves an array with post_id, published, and published_at keys. This is the code under test that will be mocked in the test example. ```php model = $model; } public function publishPost($id) { $saveData = [ 'post_id' => $id, 'published' => 1, 'published_at' => gmdate('Y-m-d H:i:s'), ]; $this->model->save($saveData); } } ``` -------------------------------- ### Runtime partial test double with makePartial Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates a runtime partial test double using makePartial(). Methods not explicitly allowed or expected will behave as on a normal instance. The example shows that foo() returns 123 initially, then after setting an expectation, bar() returns 456. ```php class Foo { function foo() { return 123; } function bar() { return $this->foo(); } } $foo = mock(Foo::class)->makePartial(); $foo->foo(); // int(123); ``` ```php $foo->shouldReceive('foo')->andReturn(456); $foo->bar(); // int(456) ``` -------------------------------- ### Using Mockery::not() matcher Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is not equal or identical to the given parameter. The example shows \Mockery::not(2) and its Hamcrest equivalent not(2). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::not(2)); // Hamcrest equivalent $mock->shouldReceive('foo') ->with(not(2)); ``` -------------------------------- ### Using Mockery::subset() matcher Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is an array containing the given array subset. The example uses \Mockery::subset(array(0 => 'foo')). It enforces both key naming and values. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::subset(array(0 => 'foo'))); ``` -------------------------------- ### Using Mockery::pattern() for regex matching Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches an argument against a regular expression using \Mockery::pattern(). The example shows a pattern '/^foo/' and its Hamcrest equivalent using matchesPattern(). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::pattern('/^foo/')); // Hamcrest equivalent $mock->shouldReceive('foo') ->with(matchesPattern('/^foo/')); ``` -------------------------------- ### Mark expectation as default with byDefault() Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Marks an expectation as a default. Default expectations are applied unless a non-default expectation is created. Later expectations immediately replace the previously defined default. Useful for setting up default mocks in unit test setup() and tweaking them later. ```php byDefault() ``` -------------------------------- ### Set minimum call count with atLeast()->times(3) Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Use atLeast() to set a minimum number of times a method should be called. The example requires at least three calls. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method') ->atLeast() ->times(3); ``` -------------------------------- ### hasValue() matcher example Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is an array containing the given value. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::hasValue(value)); ``` -------------------------------- ### any() matcher and Hamcrest anything() Source: https://docs.mockery.io/en/latest/reference/argument_validation.html Shows how to match any argument in a position using `\Mockery::any()` and its Hamcrest equivalent `anything()`. Any value passed is accepted. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive("foo") ->with(\Mockery::any()); // Hamcrest equivalent $mock->shouldReceive("foo") ->with(anything()) ``` -------------------------------- ### allows() with array Source: https://docs.mockery.io/en/latest/reference/alternative_should_receive_syntax.html Sets up method stubs with predefined return values using the allows() method with an array of method names and return values. This is equivalent to using shouldReceive() with an array. ```APIDOC ## allows() with array ### Description Sets up method stubs with predefined return values using the allows() method with an array of method names and return values. This is equivalent to using shouldReceive() with an array. ### Method allows() ### Parameters - **array** (array) - Required - An associative array mapping method names to return values. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->allows([ 'name_of_method_1' => 'return value', 'name_of_method_2' => 'return value', ]); ``` ### Response No return value. ``` -------------------------------- ### contains() matcher example Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is an array containing the listed values. The naming of keys is ignored. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::contains(value1, value2)); ``` -------------------------------- ### Mock object with ordered queries and patterns Source: https://docs.mockery.io/en/latest/getting_started/quick_reference.html Create a mock object where queries occur in a specific order with pattern matching for arguments. ```php use \Mockery\Adapter\Phpunit\MockeryTestCase; class DbTest extends MockeryTestCase { public function testOrderedQueries() { $db = \Mockery::mock('db'); $db->shouldReceive('startup')->once()->ordered(); $db->shouldReceive('query')->with('CPWR')->andReturn(12.3)->once()->ordered('queries'); $db->shouldReceive('query')->with('MSFT')->andReturn(10.0)->once()->ordered('queries'); $db->shouldReceive('query')->with(\Mockery::pattern("/^....$/"))->andReturn(3.3)->atLeast()->once()->ordered('queries'); $db->shouldReceive('finish')->once()->ordered(); // ... test code here using the mock } } ``` -------------------------------- ### Enable reflection cache Source: https://docs.mockery.io/en/latest/_sources/mockery/configuration.rst.txt Use \Mockery::getConfiguration()->enableReflectionCache() to turn reflection caching back on after disabling it. ```php \Mockery::getConfiguration()->enableReflectionCache(); ``` -------------------------------- ### allows() with method call Source: https://docs.mockery.io/en/latest/reference/alternative_should_receive_syntax.html Sets up a method stub with a predefined return value and argument matching using the allows() method with a method call. This is equivalent to using shouldReceive() with with() and andReturn(). ```APIDOC ## allows() with method call ### Description Sets up a method stub with a predefined return value and argument matching using the allows() method with a method call. This is equivalent to using shouldReceive() with with() and andReturn(). ### Method allows() ### Parameters - **method** (string) - Required - The name of the method to stub. - **arguments** (mixed) - Required - The arguments to match for the method call. - **return value** (mixed) - Required - The value to return when the method is called. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->allows() ->name_of_method_1($arg1) ->andReturn('return value'); ``` ### Response No return value. ``` -------------------------------- ### getMock() Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Returns the current mock object from an expectation chain. Useful where we prefer to keep mock setups as a single statement. ```APIDOC ## getMock() ### Description Returns the current mock object from an expectation chain. Useful where we prefer to keep mock setups as a single statement. ### Method getMock() ### Usage Example ```php $mock = \Mockery::mock('foo')->shouldReceive('foo')->andReturn(1)->getMock(); ``` ### Returns - The current mock object. ``` -------------------------------- ### Class loading initiator diagram Source: https://docs.mockery.io/en/latest/cookbook/mocking_class_within_class.html Diagram showing class loading initiators in a dependency tree. Each initiator (A, B, C) loads other classes, preventing mocking for those loaded classes. ```text A // main loading initiator |- B // another loading initiator | |-E | +-G | |- C // another loading initiator | +-F | +- D ``` -------------------------------- ### Create a spy with \Mockery::spy() Source: https://docs.mockery.io/en/latest/reference/creating_test_doubles.html Creates a spy for a class. The spy returns null for all method calls and cannot have return values set. ```php $spy = \Mockery::spy('MyClass'); ``` -------------------------------- ### allows() with array of method-return pairs Source: https://docs.mockery.io/en/latest/_sources/reference/alternative_should_receive_syntax.rst.txt Creates a mock and stubs multiple methods with predefined return values using allows() with an array. This is equivalent to shouldReceive() with the same array, and indicates that arguments are not important. ```php $mock = \Mockery::mock('MyClass'); $mock->allows([ 'name_of_method_1' => 'return value', 'name_of_method_2' => 'return value', ]); ``` ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive([ 'name_of_method_1' => 'return value', 'name_of_method_2' => 'return value', ]); ``` -------------------------------- ### Using Mockery::notAnyOf() matcher Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is not equal or identical to any of the given parameters. The example uses \Mockery::notAnyOf(1, 2). There is no Hamcrest version of notAnyOf(). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::notAnyOf(1, 2)); ``` -------------------------------- ### Declare a single method call expectation with shouldReceive Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Use shouldReceive to tell a mock object to expect a call to a specific method. This is the starting point for all other expectations and constraints. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method'); ``` -------------------------------- ### Create a mock based on a class and multiple interfaces Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates a stub or mock that is of type 'MyClass' and implements 'MyInterface' and 'OtherInterface'. The class name does not need to be first, but it is a friendly convention. ```php $mock = \Mockery::mock('MyClass, MyInterface, OtherInterface'); ``` -------------------------------- ### Create a mock based on an interface Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates a stub or mock that implements the 'MyInterface' interface. ```php $mock = \Mockery::mock('MyInterface'); ``` -------------------------------- ### Original Point and Rectangle classes with new Point() calls Source: https://docs.mockery.io/en/latest/_sources/cookbook/mocking_class_within_class.rst.txt Shows the initial App\Point and App\Rectangle classes. Rectangle::create() instantiates Point objects directly with 'new Point()' and calls setPoint() on each, then passes them to draw(). This structure prevents mocking Point because the class is autoloaded. ```php // Point.php setPoint($x1, $y1); $b = new Point(); $b->setPoint($x2, $y1); $c = new Point(); $c->setPoint($x2, $y2); $d = new Point(); $d->setPoint($x1, $y2); $this->draw([$a, $b, $c, $d]); } public function draw($points) { echo "Do something with the points"; } } ``` -------------------------------- ### Using Mockery::ducktype() matcher Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument that is an object containing the specified list of methods. The example uses \Mockery::ducktype('foo', 'bar'). There is no Hamcrest version of ducktype(). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::ducktype('foo', 'bar')); ``` -------------------------------- ### Using namedMock() with a stub class for static fetch() Source: https://docs.mockery.io/en/latest/cookbook/class_constants.html Creates a stub class FetcherStub that defines the constants, then uses namedMock() to create a mock named Fetcher based on the stub. This avoids the undefined constant error. ```php class FetcherStub { const SUCCESS = 0; const FAILURE = 1; } \Mockery::namedMock('Fetcher', 'FetcherStub') ->shouldReceive('fetch') ->andReturn(0); $myClass = new MyClass(); $myClass->doFetching(); ``` -------------------------------- ### Basic with() matcher for integer argument Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Sets up an expectation that the foo method is called with the integer 1. Mockery first tries strict === comparison, then falls back to == for primitives. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(1): ``` -------------------------------- ### PHP class method with pass-by-reference parameter Source: https://docs.mockery.io/en/latest/_sources/reference/pass_by_reference_behaviours.rst.txt Shows a PHP class method that accepts a parameter by reference and modifies it. The example demonstrates that changes to the parameter are reflected in the original variable. ```php class Foo { public function bar(&$a) { $a++; } } $baz = 1; $foo = new Foo; $foo->bar($baz); echo $baz; // will echo the integer 2 ``` -------------------------------- ### expects() with method call Source: https://docs.mockery.io/en/latest/reference/alternative_should_receive_syntax.html Sets up an expectation that a method should be called exactly once with the given arguments, using the expects() method. This is equivalent to using shouldReceive() with once(), with(), and andReturn(). ```APIDOC ## expects() with method call ### Description Sets up an expectation that a method should be called exactly once with the given arguments, using the expects() method. This is equivalent to using shouldReceive() with once(), with(), and andReturn(). ### Method expects() ### Parameters - **method** (string) - Required - The name of the method to expect. - **arguments** (mixed) - Required - The arguments to match for the method call. - **return value** (mixed) - Required - The value to return when the method is called. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->expects() ->name_of_method_1($arg1) ->andReturn('return value'); ``` ### Response No return value. ``` -------------------------------- ### Mock with multiple query calls and a single update call Source: https://docs.mockery.io/en/latest/_sources/getting_started/quick_reference.rst.txt Create a mock that expects multiple query calls returning 1, 2, 3, and a single update call with argument 5 returning NULL. ```php use \Mockery\Adapter\Phpunit\MockeryTestCase; class DbTest extends MockeryTestCase { public function testDbAdapter() { $mock = \Mockery::mock('db'); $mock->shouldReceive('query')->andReturn(1, 2, 3); $mock->shouldReceive('update')->with(5)->andReturn(NULL)->once(); // ... test code here using the mock } } ``` -------------------------------- ### Basic test with overload mock Source: https://docs.mockery.io/en/latest/_sources/cookbook/mocking_hard_dependencies.rst.txt Uses m::mock('overload:App\Service\External') to mock the hard dependency. Sets expectations for sendSomething and getSomething, then verifies the result. Requires autoloading to avoid class already exists errors. ```php shouldReceive('sendSomething') ->once() ->with($param); $externalMock->shouldReceive('getSomething') ->once() ->andReturn('Tested!'); $service = new \App\Service(); $result = $service->callExternalService($param); $this->assertSame('Tested!', $result); } } ``` -------------------------------- ### Register Mockery autoloader in Bootstrap.php Source: https://docs.mockery.io/en/latest/_sources/reference/phpunit_integration.rst.txt Add this to your test suite's Bootstrap.php or TestHelper.php to use Mockery's autoloader, avoiding require_once() calls in tests. Ensure Mockery is on your include_path. ```php require_once 'Mockery/Loader.php'; require_once 'Hamcrest/Hamcrest.php'; $loader = new \Mockery\Loader; $loader->register(); ``` -------------------------------- ### Mock expectation style with Mockery::mock Source: https://docs.mockery.io/en/latest/reference/spies.html Shows the Arrange-Expect-Act-Assert style using a mock. The mock is set up with an expectation before acting on the SUT, then Mockery::close() asserts the expectation was met. ```php // arrange $mock = \Mockery::mock('MyDependency'); $sut = new MyClass($mock); // expect $mock->shouldReceive('foo') ->once() ->with('bar'); // act $sut->callFoo(); // assert \Mockery::close(); ``` -------------------------------- ### Mocking Protected Methods with shouldAllowMockingProtectedMethods() Source: https://docs.mockery.io/en/latest/_sources/reference/protected_methods.rst.txt Use shouldAllowMockingProtectedMethods() to enable mocking of protected methods for a specific class. The example defines MyClass with a protected foo() method, then creates a mock and sets an expectation for foo(). ```php class MyClass { protected function foo() { } } $mock = \Mockery::mock('MyClass') ->shouldAllowMockingProtectedMethods(); $mock->shouldReceive('foo'); ``` -------------------------------- ### Set maximum call count with atMost()->times(3) Source: https://docs.mockery.io/en/latest/_sources/reference/expectations.rst.txt Use atMost() to set a maximum number of times a method should be called. The example allows no more than three calls, and zero calls still meets the expectation. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method') ->atMost() ->times(3); ``` -------------------------------- ### Publish a post with Mockery::on() service class Source: https://docs.mockery.io/en/latest/cookbook/mockery_on.html This is a service class that publishes a post by saving data with a mocked model. It contains a constructor that takes a model and a publishPost method that sets the post_id, published flag to 1, and the current UTC timestamp. ```php model = $model; } public function publishPost($id) { $saveData = [ 'post_id' => $id, 'published' => 1, 'published_at' => gmdate('Y-m-d H:i:s'), ]; $this->model->save($saveData); } } ``` -------------------------------- ### expects() with once expectation Source: https://docs.mockery.io/en/latest/_sources/reference/alternative_should_receive_syntax.rst.txt Sets up an expectation that a method is called exactly once using expects(). This is equivalent to shouldReceive() with once() and with(). ```php $mock = \Mockery::mock('MyClass'); $mock->expects() ->name_of_method_1($arg1) ->andReturn('return value'); ``` ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method_1') ->once() ->with($arg1) ->andReturn('return value'); ``` -------------------------------- ### Using withArgs() with a closure Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Passes a closure to withArgs() to validate all arguments. The closure receives all arguments and must return true for a match. The example shows a closure that handles optional parameters, allowing calls with or without the optional argument. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive("foo") ->withArgs(closure); ``` ```php $closure = function ($odd, $even, $sum = null) { $result = ($odd % 2 != 0) && ($even % 2 == 0); if (!is_null($sum)) { return $result && ($odd + $even == $sum); } return $result; }; $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo')->withArgs($closure); $mock->foo(1, 2); // It matches the expectation: the optional argument is not needed $mock->foo(1, 2, 3); // It also matches the expectation: the optional argument pass the validation $mock->foo(1, 2, 4); // It doesn't match the expectation: the optional doesn't pass the validation ``` -------------------------------- ### Create a mock based on an existing class Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates a stub or mock that inherits the type of 'MyClass', so it passes type hints and instanceof checks for that class. ```php $mock = \Mockery::mock('MyClass'); ``` -------------------------------- ### Using Mockery::on() closure matcher Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches an argument when the closure returns true. The example shows a closure checking if the argument is even. Calls with matching arguments succeed, while non-matching ones throw NoMatchingExpectationException. There is no Hamcrest version of on(). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->with(\Mockery::on(function ($argument) { if ($argument % 2 == 0) { return true; } return false; })); $mock->foo(4); // matches the expectation $mock->foo(3); // throws a NoMatchingExpectationException ``` -------------------------------- ### allows() - Method Chaining Source: https://docs.mockery.io/en/latest/_sources/reference/alternative_should_receive_syntax.rst.txt Creates a stub for a single method with argument matching and a predefined return value. ```APIDOC ## allows() - Method Chaining ### Description Creates a stub for a single method with argument matching and a predefined return value. ### Method allows() ### Parameters - **method** (string) - Required - The method name to stub. - **args** (mixed) - Optional - Arguments to match for the method call. - **andReturn** (mixed) - Required - The return value to set. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->allows() ->name_of_method_1($arg1) ->andReturn('return value'); ``` ### Response No return value specified. ``` -------------------------------- ### Create a test double implementing an interface Source: https://docs.mockery.io/en/latest/_sources/getting_started/quick_reference.rst.txt Create a test double that implements a specific interface by passing a comma-separated string to Mockery::mock(). ```php $testDouble = \Mockery::mock('MyClass, MyInterface'); ``` -------------------------------- ### Set and get internal class method parameter maps Source: https://docs.mockery.io/en/latest/_sources/mockery/configuration.rst.txt Use \Mockery::getConfiguration()->setInternalClassMethodParamMap() and getInternalClassMethodParamMap() to define parameter signatures for methods of internal PHP classes (e.g., SPL, PECL extensions). Reflection cannot analyze internal class parameters, so this is needed mainly for pass-by-reference parameters, where the '&' symbol must be included. Not available in PHP 8. ```php \Mockery::getConfiguration()->setInternalClassMethodParamMap($class, $method, array $paramMap) \Mockery::getConfiguration()->getInternalClassMethodParamMap($class, $method) ``` -------------------------------- ### Create a generated partial test double with constructor arguments Source: https://docs.mockery.io/en/latest/_sources/reference/partial_mocks.rst.txt Creates a generated partial mock for MyNamespace\MyClass, mocking only the foo() method, and passes constructor arguments ($arg1, $arg2) since unmocked methods may rely on them. ```php $mock = \Mockery::mock('MyNamespace\MyClass[foo]', array($arg1, $arg2)); ``` -------------------------------- ### Mock object returning a sequence of values Source: https://docs.mockery.io/en/latest/_sources/getting_started/quick_reference.rst.txt Create a mock that returns predefined values for method calls, using an array of method names to return values. ```php use \Mockery\Adapter\Phpunit\MockeryTestCase; class SimpleTest extends MockeryTestCase { public function testSimpleMock() { $mock = \Mockery::mock(array('pi' => 3.1416, 'e' => 2.71)); $this->assertEquals(3.1416, $mock->pi()); $this->assertEquals(2.71, $mock->e()); } } ``` -------------------------------- ### Expect a method call with argument and return value Source: https://docs.mockery.io/en/latest/_sources/getting_started/quick_reference.rst.txt Set an expectation that 'foo' is called once with a specific argument and returns a specific value. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('foo') ->once() ->with($arg) ->andReturn($returnValue); ``` -------------------------------- ### Create an unnamed stub or mock object Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates a stub or mock with no name. Not recommended by the documentation. ```php $mock = \Mockery::mock(); ``` -------------------------------- ### Create a generated partial test double with method list Source: https://docs.mockery.io/en/latest/_sources/reference/partial_mocks.rst.txt Creates a traditional partial mock where only the foo() and bar() methods of MyClass are mocked; all other methods remain unmocked. Expectations must be defined for the mocked methods. ```php $mock = \Mockery::mock('MyClass[foo,bar]'); ``` -------------------------------- ### Create a stub or mock object named 'foo' Source: https://docs.mockery.io/en/latest/_sources/reference/creating_test_doubles.rst.txt Creates the loosest form of mock possible, an instance of \Mockery\MockInterface. The identifier 'foo' is used as the test double's name. ```php $mock = \Mockery::mock('foo'); ``` -------------------------------- ### type() matcher for PHP resource and Hamcrest equivalents Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches arguments that are PHP resources using \Mockery::type('resource'). Hamcrest provides resourceValue() and typeOf('resource') as equivalents. ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive("foo") ->with(\Mockery::type('resource')); // Hamcrest equivalents $mock->shouldReceive("foo") ->with(resourceValue()); $mock->shouldReceive("foo") ->with(typeOf('resource')); ``` -------------------------------- ### allows() - Array Syntax Source: https://docs.mockery.io/en/latest/_sources/reference/alternative_should_receive_syntax.rst.txt Creates stubs for multiple methods with predefined return values, ignoring arguments and call count. ```APIDOC ## allows() - Array Syntax ### Description Creates stubs for multiple methods with predefined return values, ignoring arguments and call count. ### Method allows() ### Parameters - **array** (array) - Required - Associative array mapping method names to return values. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->allows([ 'name_of_method_1' => 'return value', 'name_of_method_2' => 'return value', ]); ``` ### Response No return value specified. ``` -------------------------------- ### Working test: mocking newPoint() to return Point mock Source: https://docs.mockery.io/en/latest/_sources/cookbook/mocking_class_within_class.rst.txt This test mocks the newPoint() method to return the App\Point mock, so setPoint() throws as expected. The test passes because the mock is used instead of the real class. This approach avoids global state pollution. ```php shouldReceive("setPoint")->andThrow(Exception::class); $rect = Mockery::mock("App\Rectangle")->makePartial(); $rect->shouldReceive("draw"); // pass the App\Point mock into App\Rectangle as an alternative // to using new App\Point() in-place. $rect->shouldReceive("newPoint")->andReturn($point); $this->expectException(Exception::class); $rect->create(0, 0, 100, 100); Mockery::close(); } } ``` -------------------------------- ### Create a proxied partial mock with a real instance Source: https://docs.mockery.io/en/latest/_sources/reference/partial_mocks.rst.txt Creates a proxied partial mock by passing a real instance of MyClass. This allows mocking final methods because the proxy intercepts calls and reroutes them to the proxied object for methods without expectations. Note that typehint checks for the mocked class will fail. ```php $mock = \Mockery::mock(new MyClass); ``` -------------------------------- ### allows() with argument matching Source: https://docs.mockery.io/en/latest/_sources/reference/alternative_should_receive_syntax.rst.txt Stubs a single method with argument matching using allows() and andReturn(). This is equivalent to shouldReceive() with with() and andReturn(). ```php $mock = \Mockery::mock('MyClass'); $mock->allows() ->name_of_method_1($arg1) ->andReturn('return value'); ``` ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive('name_of_method_1') ->with($arg1) ->andReturn('return value'); ``` -------------------------------- ### Mock instance class constants with namedMock Source: https://docs.mockery.io/en/latest/_sources/cookbook/class_constants.rst.txt This workflow shows the same namedMock approach when Fetcher::fetch() is not static. The first block defines a Fetcher with an instance method and MyClass that receives the fetcher as a dependency. The second block creates a mock named 'Fetcher' based on a stub that defines the constants, then passes it to MyClass. ```php class Fetcher { const SUCCESS = 0; const FAILURE = 1; public function fetch() { // Fetcher gets something for us from somewhere... return self::SUCCESS; } } class MyClass { public function doFetching($fetcher) { $response = $fetcher->fetch(); if ($response == Fetcher::SUCCESS) { echo "Thanks!" . PHP_EOL; } else { echo "Try again!" . PHP_EOL; } } } ``` ```php class FetcherStub { const SUCCESS = 0; const FAILURE = 1; } $mock = \Mockery::mock('Fetcher', 'FetcherStub') $mock->shouldReceive('fetch') ->andReturn(0); $myClass = new MyClass(); $myClass->doFetching($mock); ``` -------------------------------- ### expects() with twice() Source: https://docs.mockery.io/en/latest/reference/alternative_should_receive_syntax.html Sets up an expectation that a method should be called exactly twice with the given arguments, using the expects() method and the twice() modifier. This is equivalent to using shouldReceive() with twice(), with(), and andReturn(). ```APIDOC ## expects() with twice() ### Description Sets up an expectation that a method should be called exactly twice with the given arguments, using the expects() method and the twice() modifier. This is equivalent to using shouldReceive() with twice(), with(), and andReturn(). ### Method expects() ### Parameters - **method** (string) - Required - The name of the method to expect. - **arguments** (mixed) - Required - The arguments to match for the method call. - **return value** (mixed) - Required - The value to return when the method is called. ### Request Example ```php $mock = \Mockery::mock('MyClass'); $mock->expects() ->name_of_method_1($arg1) ->twice() ->andReturn('return value'); ``` ### Response No return value. ``` -------------------------------- ### Mockery test with on() matcher for save() Source: https://docs.mockery.io/en/latest/_sources/cookbook/mockery_on.rst.txt Shows how to mock the model and set an expectation on save() using Mockery::on() with a closure that validates the array argument. The closure checks post_id, published, and published_at keys; if any check fails, Mockery throws NoMatchingExpectationException. ```php shouldReceive('save') ->once() ->with(\Mockery::on(function ($argument) use ($postId) { $postIdIsSet = isset($argument['post_id']) && $argument['post_id'] === $postId; $publishedFlagIsSet = isset($argument['published']) && $argument['published'] === 1; $publishedAtIsSet = isset($argument['published_at']); return $postIdIsSet && $publishedFlagIsSet && $publishedAtIsSet; })); $service = new \Service\Post($modelMock); $service->publishPost($postId); \Mockery::close(); ``` -------------------------------- ### Mock class constants with setConstantsMap Source: https://docs.mockery.io/en/latest/_sources/cookbook/class_constants.rst.txt This workflow shows how to mock class constants using the constants map configuration. The first block defines a class with constants. The second block sets a constants map that replaces the constant values with strings, then creates a mock and dumps the new constant values. ```php class Fetcher { const SUCCESS = 0; const FAILURE = 1; public function fetch() { // Fetcher gets something for us from somewhere... return self::SUCCESS; } } ``` ```php \Mockery::getConfiguration()->setConstantsMap([ 'Fetcher' => [ 'SUCCESS' => 'success', 'FAILURE' => 'fail', ] ]); $mock = \Mockery::mock('Fetcher'); var_dump($mock::SUCCESS); // (string) 'success' var_dump($mock::FAILURE); // (string) 'fail' ``` -------------------------------- ### Expect all queries before any updates Source: https://docs.mockery.io/en/latest/_sources/getting_started/quick_reference.rst.txt Use ordered() to ensure that all query calls happen before the update call. ```php use \Mockery\Adapter\Phpunit\MockeryTestCase; class DbTest extends MockeryTestCase { public function testQueryAndUpdateOrder() { $mock = \Mockery::mock('db'); $mock->shouldReceive('query')->andReturn(1, 2, 3)->ordered(); $mock->shouldReceive('update')->andReturn(NULL)->once()->ordered(); // ... test code here using the mock } } ``` -------------------------------- ### Argument matching with array of arguments Source: https://docs.mockery.io/en/latest/_sources/reference/spies.rst.txt Shows argument matching by passing an array of arguments to shouldHaveReceived. ```php $spy->shouldHaveReceived('foo', ['bar']); ``` -------------------------------- ### any() matcher to accept any argument Source: https://docs.mockery.io/en/latest/_sources/reference/argument_validation.rst.txt Matches any argument in that position, regardless of type or value. The Hamcrest equivalent is anything(). ```php $mock = \Mockery::mock('MyClass'); $mock->shouldReceive("foo") ->with(\Mockery::any()); // Hamcrest equivalent $mock->shouldReceive("foo") ->with(anything()) ```