Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when mocking interfaces in PHP using Mockery

I have run into a problem when mocking Interfaces using Mockery in PHP (im using the laravel framework but I'm not sure this is relevant.

I have defined an interface

<?php namespace MyNamespace\SomeSubFolder;

interface MyInterface {

    public function method1();

}

And I have a class that typehints that interface on one of the methods...

<?php namespace MyNamespace\SomeSubFolder;

use MyNamespace\SomeSubFolder\MyInterface;

class MyClass {

    public function execute(MyInterface $interface)
    {
         //does some stuff here

    }
}

...and I am trying to test MyClass. I have created a test that looks something like this:

public function testExecute()
{

    $mock = Mockery::mock('MyNamespace\SomeSubFolder\MyInterface');

    $mock->shouldReceive('method1')
         ->andReturn('foo');

    $myClass = new MyClass();

    $myClass->execute($mock);

}

When I run the test I receive the message

'ErrorException: Argument 1 passed to MyClass::execute must be an instance of MyNamespace\SomeSubFolder\MyInterface, instance of Mockery_123465456 given....'

I have no idea why.

Within the test I have tried the following :

$this->assertTrue(interface_exists('MyNamespace\SomeSubFolder\MyInterface'));

$this->assertTrue($mock instanceof MyInterface);

and both return true, so it appears as if I have created and instance that implements the interface, but when I call the method on the class it disagrees. Any ideas???

like image 982
Cookstaar Avatar asked Oct 20 '13 15:10

Cookstaar


1 Answers

You should call mock() method at the and of mock declaration.

$mock = Mockery::mock('MyNamespace\SomeSubFolder\MyInterface');

$mock->shouldReceive('method1')
     ->andReturn('foo')
     ->mock();
like image 180
Hexogen Avatar answered Nov 04 '22 23:11

Hexogen