Error validating argument against Mockery object

Let's look at examples of classes (apologies for being so confusing, but it's as subtle as possible):

class RecordLookup
{
    private $records = [
        13 => 'foo',
        42 => 'bar',
    ];

    function __construct($id)
    {
        $this->record = $this->records[$id];
    }

    public function getRecord()
    {
        return $this->record;
    }
}

class RecordPage
{
    public function run(RecordLookup $id)
    {
        return "Record is " . $id->getRecord();
    }
}

class App
{
    function __construct(RecordPage $page, $id)
    {
        $this->page = $page;
        $this->record_lookup = new RecordLookup($id);
    }

    public function runPage()
    {
        return $this->page->run($this->record_lookup);
    }
}

In which I want to test the application while taunting RecordPage:

class AppTest extends \PHPUnit_Framework_TestCase
{
    function testAppRunPage()
    {
        $mock_page = \Mockery::mock('RecordPage');

        $mock_page
            ->shouldReceive('run')
            ->with(new RecordLookup(42))
            ->andReturn('bar');

        $app = new App($mock_page, 42);

        $this->assertEquals('Record is bar', $app->runPage());
    }
}

Note: The expected argument of the object ->with(new RecordLookup(42)).

I would expect this to pass, however the Mockery returns throws No matching handler found for Mockery_0_RecordPage::run(object(RecordLookup)). Either the method was unexpected or its arguments matched no expected argument list for this method.

I assume this is due to the fact that for arguments expected through with()and new RecordLookup(42) === new RecordLookup(42), strict comparison is used, evaluated as false. A note new RecordLookup(42) == new RecordLookup(42)is evaluated as true, so if someone softened the comparison, that would fix my problem.

Is there a way to handle the expected instance arguments in Mockery? Maybe I'm using it incorrectly?

+4
1

, RecordLookup ():

$mock_page
        ->shouldReceive('run')
        ->with(\Mockery::type('RecordLookup'))
        ->andReturn('bar');

RecordLookup. , 42, :

$mock_page
        ->shouldReceive('run')
        ->with(\Mockery::on(function($argument) {
            return 
                 $argument instanceof RecordLookup && 
                 'bar' == $argument->getRecord()
            ;
        }))
        ->andReturn('bar');

.

+8

Source: https://habr.com/ru/post/1585102/


All Articles