Error when mocking interfaces in PHP using Mockery

I had a problem mocking interfaces using Mockery in PHP (im uses larvel framework, but I'm not sure if this is relevant.

I defined the interface

<?php namespace MyNamespace\SomeSubFolder; interface MyInterface { public function method1(); } 

And I have a class that typehints this interface for 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'm trying to check out MyClass. I 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 get a message

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

I have no idea why.

As part of the test, I tried the following:

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

and both return true, so it looks like I created an instance that implements the interface, but when I call the class method, it does not agree. Any ideas ???

+7
php laravel mockery
source share
2 answers

You must call the mock () method in the mock declaration.

 $mock = Mockery::mock('MyNamespace\SomeSubFolder\MyInterface'); $mock->shouldReceive('method1') ->andReturn('foo') ->mock(); 
+10
source share

I think the problem is with loading the PHP class. The class MyNamespace \ SomeSubFolder \ MyInterface is not available from your test file.

You will need to change your composer.json to autoload this namespace or you will need require_once ('path / to / file / containing / namespace / MyInterface.php') at the top of the test.

Although, when you tried to use interface_exists, it seemed to go away. It may also happen that you mistakenly wrote your class with names when you mocked it. I also made this mistake.

In any case, Mockery cannot see that the class exists, so it just comes up with it.

Can you provide a complete source of testing?

-one
source share

All Articles