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

2

6

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';
                })
            );
Reactivate answered 19/8, 2015 at 13:47 Comment(0)
R
4

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')
                );
Reactivate answered 19/8, 2015 at 14:21 Comment(2)
Is there any way to test that array has two keys?Amoebic
@DimitryK Hamcrest let's you combine conditions which may work. E.g allOf(hasEntry('my_key1', 'my_value1'), hasEntry('my_key2', 'my_entry2')). Also, Mockery has Mockery::subset() which may also be what you want. E.g. \Mockery::subset(['my_key1' => 'my_value1', 'my_key2' => 'my_entry2']).Seeger
M
2

If you are interested in another solution you can check Ouzo mocking.

Simply you can do this:

//creating mock
$mock = Mock::create('MockTestClass');

//call mock
$mock->test(['key1' => 'value1', 'key2' => 'value2']);

//asserts (verification)
Mock::verify($mock)->test(Mock::argThat()->extractField('key1')->equals('value1'));
Mock::verify($mock)->test(Mock::argThat()->extractField('key2')->equals('value2'));
Marvismarwin answered 19/8, 2015 at 19:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.