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

自作多情 提交于 2019-12-21 06:58:29

问题


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?


回答1:


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();



回答2:


Ok problem solved by using standard PhpUnit Mock library

This works:

$mediaPublisherMock = $this->getMock('Mrok\Model\MessagePublisher', array('publish'), array(), '', false);
$mediaPublisherMock->expects($this->once())
    ->method('publish');

Why I did not start from this ;)




回答3:


I believe $expectation should be your class, MessagePublisher



来源:https://stackoverflow.com/questions/12876849/mockery-call-user-func-array-expects-parameter-1-to-be-a-valid-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!