Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mock an interface implementation with PHPUnit?

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?

<?php 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.

like image 711
Dmitry Minkovsky Avatar asked Sep 24 '13 04:09

Dmitry Minkovsky


People also ask

Can you mock an interface?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.

What is mock PHPUnit?

Likewise, PHPUnit mock object is a simulated object that performs the behavior of a part of the application that is required in the unit test. The developers control the mock object by defining the pre-computed results on the actions.

Can you mock without an interface?

Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.


1 Answers

Instead of

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

use

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

or

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

Totally works!

like image 101
Dmitry Minkovsky Avatar answered Sep 23 '22 23:09

Dmitry Minkovsky