我可以使用PHPUnit模拟接口实现吗?

Dmi*_*sky 38 php phpunit interface mocking

我有一个我想要模拟的界面.我知道我可以模拟该接口的实现,但有没有办法只是模拟接口?

<?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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到的是:

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
Run Code Online (Sandbox Code Playgroud)

有趣的是,PHPUnit,模拟接口和instanceof会建议这可行.

Dmi*_*sky 47

代替

$http_client = $this->getMockBuilder(Cpm\Http\IClient::class);
Run Code Online (Sandbox Code Playgroud)

使用

$http_client = $this->getMock(Cpm\Http\IClient::class);
Run Code Online (Sandbox Code Playgroud)

要么

$http_client = $this->getMockBuilder(Cpm\Http\IClient::class)->getMock();
Run Code Online (Sandbox Code Playgroud)

完全有效!

  • 我不得不使用$ mockBuilder-> setMethods(['all','my','interface','methods'])来使它工作.但是,是完美的.谢谢您的帮助. (8认同)
  • 只有 $this-&gt;getMockBuilder(...)-&gt;getMock() 对我有用 PHPUnit 7.5.1 (2认同)

Fra*_*rzi 14

以下适用于我:

$myMockObj = $this->createMock(MyInterface::class);
Run Code Online (Sandbox Code Playgroud)