Mockery - call_user_func_array() expects parameter 1 to be a valid callback

mrok picture mrok · Oct 13, 2012 · Viewed 7.5k times · Source

I have a class I need to mock:

class MessagePublisher
{
    /**
     * @param \PhpAmqpLib\Message\AMQPMessage $msg
     * @param string $exchange - if not provided then one passed in constructor is used
     * @param string $routing_key
     * @param bool $mandatory
     * @param bool $immediate
     * @param null $ticket
     */
    public function publish(AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null)
    {
        if (empty($exchange)) {
            $exchange = $this->exchangeName;
        }

        $this->channel->basic_publish($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket);
    }
}

I am using Mockery 0.7.2

$mediaPublisherMock = \Mockery::mock('MessagePublisher')
    ->shouldReceive('publish')
    ->withAnyArgs()
    ->times(3)
    ->andReturn(null);

unfortunately my tests failed, due to this error

call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'publish' in /vendor/mockery/mockery/library/Mockery/CompositeExpectation.php on line 54

I have tried to debug I found that tests fails in this code

public function __call($method, array $args)
{
    foreach ($this->_expectations as $expectation) {
        call_user_func_array(array($expectation, $method), $args);
    }
    return $this;
}

where
$method = 'publish'
$args = array()
$expectation is instance of Mockery\Expectation object ()

I am using php 5.3.10 - any idea what is wrong?

Answer

Dave Marshall picture Dave Marshall · Oct 17, 2012

This is happening because you are assigning a mock expectation to $mediaPublisherMock, rather than the mock itself. Try adding the getMock method to the end of that call, like:

$mediaPublisherMock = \Mockery::mock('MessagePublisher')
    ->shouldReceive('publish')
    ->withAnyArgs()
    ->times(3)
    ->andReturn(null)
    ->getMock();