49

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

<?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、模拟接口和 instanceof表明这可能会起作用。

4

3 回答 3

60

代替

$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();

完全有效!

于 2013-09-24T04:29:29.543 回答
16

以下对我有用:

$myMockObj = $this->createMock(MyInterface::class);
于 2016-11-08T08:21:04.830 回答
1
$http_client = $this->getMockBuilder(Cpm\Http\IClient::class)
                    ->setMockClassName('SomeClassName')
                    ->getMock();

setMockClassName ()在某些情况下可用于解决此问题。

于 2019-06-10T21:47:29.057 回答