我有一个我想要模拟的界面。我知道我可以模拟该接口的实现,但有没有办法只是模拟接口?
<?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, mocked interfaces, and instanceof表明这可行。
答案 0 :(得分:43)
而不是
$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();
完全有效!
答案 1 :(得分:12)
以下适用于我:
$myMockObj = $this->createMock(MyInterface::class);
答案 2 :(得分:0)
$http_client = $this->getMockBuilder(Cpm\Http\IClient::class)
->setMockClassName('SomeClassName')
->getMock();
在某些情况下, setMockClassName()可用于解决此问题。