Skip to content

Instantly share code, notes, and snippets.

@dnaber-de
Created February 8, 2016 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnaber-de/3c0c36603fee173b0fa5 to your computer and use it in GitHub Desktop.
Save dnaber-de/3c0c36603fee173b0fa5 to your computer and use it in GitHub Desktop.
Approach on Monkey::action expects different values on consecutive calls
<?php
Brain\Monkey::actions()
->expectFired( 'do_something' )
->twice()
->withArgs(
[
'first',
'second'
]
);
do_action( 'do_something', 'first' );
do_action( 'do_something', 'second' );
//Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0__do_do_something::do_action_do_something("first"). Either the method was unexpected or its arguments matched no expected argument list for this method
@gmazzap
Copy link

gmazzap commented Feb 8, 2016

@dnaber-de because that test you are testing

do_action( 'do_something', 'first', 'second' );

In fact withArgs([$arg1, $arg2]) is equal to with($arg1, $arg2).

Surely you can do:

Brain\Monkey::actions()
  ->expectFired( 'do_something' )
  ->twice()
  ->with(\Mockery::anyOf('first', 'second'));

But this does not test the order.

this should be possible as well:

Brain\Monkey::actions()
  ->expectFired( 'do_something' )
  ->once()
  ->with('first');

Brain\Monkey::actions()
  ->expectFired( 'do_something' )
  ->once()
  ->with('second');

This is possible for normal objects, if it does not work, it is a Brain Monkey bug: an issue would be much appreciated.

An alternative solution is the "manual" way:

Brain\Monkey::actions()
  ->expectFired( 'do_something' )
  ->twice()
  ->whenHappen(function($arg) {
        static $i = -1;
        $i++;
        $expected = ['first', 'second'];
        $this->assertSame($expected[$i], $arg);
  });

@gmazzap
Copy link

gmazzap commented Feb 8, 2016

It seems that this issue mockery/mockery#459 I opened an year ago, has been implemented. In next version of Mockery the manual version can become:

Brain\Monkey::actions()
  ->expectFired( 'do_something' )
  ->twice()
  ->withArgs(function($arg) {
        static $i = -1;
        $i++;
        $expected = ['first', 'second'];
        $this->asssertSame($expected[$i], $arg);
  });

So you can use whenHappen for what it is intentended to be used...

@dnaber-de
Copy link
Author

Thanks a lot, Giuseppe!

This is possible for normal objects, if it does not work, it is a Brain Monkey bug: an issue would be much appreciated.
I'll figure out and will create an issue if there's one.

Yes, currently went with something like

Brain\Monkey::actions()
    ->expectFired( 'do_something' )
    ->twice()
    ->with( Mockery::on( function( $arg ) {
        // test $arg here
        return TRUE;
    } ) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment