Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockery: test if argument is an array containing a key/value pair

How can I use mockery and hamcrest to assert that when a method of a mock object is called, one of the arguments passed to it is an array containing a key/value pair?

For example, my test code might look like this:

$mock = m::mock('\Jodes\MyClass');

$mock   ->shouldReceive('myMethod')
        ->once()
        ->with(
                    arrayContainsPair('my_key', 'my_value')
                );

I know I could write it with a closure, but I was just wondering if there's another way of making it read slightly better:

$mock   ->shouldReceive('myMethod')
        ->once()
        ->with(
                m::on(function($options){
                    return 
                        is_array($options) &&
                        isset($options['my_key']) &&
                        $options['my_key'] == 'my_val';
                })
            );
like image 599
CL22 Avatar asked Aug 19 '15 13:08

CL22


1 Answers

I found the answer by looking through the Hamcrest PHP code here,

The function name is given away in the doc comment:

 * @factory hasEntry

So my code will look like this:

$mock   ->shouldReceive('myMethod')
        ->once()
        ->with(
                    hasEntry('my_key', 'my_value')
                );
like image 140
CL22 Avatar answered Sep 21 '22 23:09

CL22