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

2022-08-30 10:37:01

我有一个界面,我想嘲笑一下。我知道我可以模拟该接口的实现,但是有没有办法模拟该接口?

<?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);
  }
}

我在这里得到的是:

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

有趣的是,PHPUnit,模拟接口和实例of表明这可能有效。


答案 1

而不是

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

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

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

完全有效!


答案 2

以下内容对我有用:

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

推荐