Home » Php » Can I mock an interface implementation with PHPUnit?

Can I mock an interface implementation with PHPUnit?

Posted by: admin December 5, 2017 Leave a comment


I’ve got an interface I’d like to mock. I know I can mock an implementation of that interface, but is there a way to just mock the interface?

require __DIR__ . '/../vendor/autoload.php';

use My\Http\IClient as IHttpClient;  // The interface
use My\SomethingElse\Client as SomethingElseClient;

class SomethingElseClientTest extends PHPUnit_Framework_TestCase {
  public function testPost() {
    $url = 'some_url';
    $http_client = $this->getMockBuilder('Cpm\Http\IClient');
    $something_else = new SomethingElseClient($http_client, $url);

What I get here is:

1) SomethingElseTest::testPost
Argument 1 passed to Cpm\SomethingElse\Client::__construct() must be an instance of
My\Http\IClient, instance of PHPUnit_Framework_MockObject_MockBuilder given, called in
$PATH_TO_PHP_TEST_FILE on line $NUMBER and defined

Interestingly, PHPUnit, mocked interfaces, and instanceof would suggest this might work.


Instead of

http_client = $this->getMockBuilder('Cpm\Http\IClient');


http_client = $this->getMock('Cpm\Http\IClient');


http_client = $this->getMockBuilder('Cpm\Http\IClient')->getMock();

Totally works!


The following works for me:

$myMockObj = $this->createMock(MyInterface::class);

Leave a Reply

Your email address will not be published. Required fields are marked *