如何解决PHPUnit和模拟依赖
我正在为Service类编写一个测试。如下所示,我的Service类使用Gateway类。我想在我的一项测试中模拟Gateway类上的getSomething()
的输出。
我尝试使用存根(createStub
)和模拟(getMockBuilder
),但PHPUnit无法产生所需的结果。
我的课程:
<?php
class GatewayClass
{
private $client = null;
public function __construct(Client $client)
{
$this->client = $client->getClient();
}
public function getSomething()
{
return 'something';
}
}
<?php
class Service
{
private $gateway;
public function __construct(Client $client)
{
$this->gateway = new Gateway($client);
}
public function getWorkspace()
{
return $this->gateway->getSomething();
}
}
(该项目还没有DI容器)
解决方法
要模拟Gateway
类,必须将其注入Service
。
class Service
{
private $gateway;
public function __construct(Gateway $gateway)
{
$this->gateway = $gateway;
}
public function getWorkspace()
{
return $this->gateway->getSomething();
}
}
class ServiceTest
{
public function test()
{
$gateway = $this->createMock(Gateway::class);
$gateway->method('getSomething')->willReturn('something else');
$service = new Service($gateway);
$result = $service->getWorkspace();
self::assertEquals('something else',$result);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。