Skip to content

Commit

Permalink
Merge pull request #1020 from jasonmccreary/capture
Browse files Browse the repository at this point in the history
Add capture argument matcher
  • Loading branch information
robertbasic committed Nov 20, 2019
2 parents 61625cd + b4fce4b commit 5963050
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
21 changes: 21 additions & 0 deletions docs/reference/argument_validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,27 @@ methods to call.

There is no Hamcrest version of the ``ducktype()`` matcher.

Capturing Arguments
-------------------

If we want to perform multiple validations on a single argument, the ``capture``
matcher provides a streamlined alternative to using the ``on()`` matcher.
It accepts a variable which the actual argument will be assigned.

.. code-block:: php
$mock = \Mockery::mock('MyClass');
$mock->shouldReceive("foo")
->with(\Mockery::capture($bar));
This will assign *any* argument passed to ``foo`` to the local ``$bar`` variable to
then perform additional validation using assertions.

.. note::

The ``capture`` matcher always evaluates to ``true``. As such, we should always
perform additional argument validation.

Additional Argument Matchers
----------------------------

Expand Down
17 changes: 17 additions & 0 deletions library/Mockery.php
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,23 @@ public static function hasValue($val)
return new \Mockery\Matcher\HasValue($val);
}

/**
* Return instance of CLOSURE matcher.
*
* @param $reference
*
* @return \Mockery\Matcher\Closure
*/
public static function capture(&$reference)
{
$closure = function ($argument) use (&$reference) {
$reference = $argument;
return true;
};

return new \Mockery\Matcher\Closure($closure);
}

/**
* Return instance of CLOSURE matcher.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/Mockery/ExpectationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,25 @@ public function testHasValueConstraintThrowsExceptionWhenConstraintUnmatched()
Mockery::close();
}

public function testCaptureStoresArgumentOfTypeScalar_ClosureEvaluatesToTrue()
{
$temp = null;
$this->mock->shouldReceive('foo')->with(Mockery::capture($temp))->once();
$this->mock->foo(4);

$this->assertSame(4, $temp);
}

public function testCaptureStoresArgumentOfTypeArgument_ClosureEvaluatesToTrue()
{
$object = new stdClass();
$temp = null;
$this->mock->shouldReceive('foo')->with(Mockery::capture($temp))->once();
$this->mock->foo($object);

$this->assertSame($object, $temp);
}

public function testOnConstraintMatchesArgument_ClosureEvaluatesToTrue()
{
$function = function ($arg) {
Expand Down

0 comments on commit 5963050

Please sign in to comment.