问题描述
我正在为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);
}
}