php 我可以用 PHPUnit 模拟接口实现吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18972901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I mock an interface implementation with PHPUnit?
提问by Dmitry Minkovsky
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 instanceofwould suggest this might work.
有趣的是,PHPUnit、模拟接口和 instanceof表明这可能有效。
回答by Dmitry Minkovsky
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!
完全有效!
回答by Francesco Borzi
The following works for me:
以下对我有用:
$myMockObj = $this->createMock(MyInterface::class);
回答by kervin
$http_client = $this->getMockBuilder(Cpm\Http\IClient::class)
->setMockClassName('SomeClassName')
->getMock();
The setMockClassName()can be used to fix this in some circumstances.
该setMockClassName()可用于在某些情况下解决这一问题。