我正在为服务类编写一个测试。正如您在下面看到的,我的服务类使用 Gateway 类。我想在我的一个测试中模拟网关类的输出。getSomething()我尝试使用存根()和模拟(),但PHPUnit没有产生预期的结果。createStubgetMockBuilder我的课程:<?phpclass GatewayClass{ private $client = null; public function __construct(Client $client) { $this->client = $client->getClient(); } public function getSomething() { return 'something'; }}<?phpclass Service{ private $gateway; public function __construct(Client $client) { $this->gateway = new Gateway($client); } public function getWorkspace() { return $this->gateway->getSomething(); }}(此项目还没有 DI 容器)
1 回答
UYOU
TA贡献1878条经验 获得超4个赞
要模拟您的类,您必须将其注入 .GatewayService
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);
}
}
- 1 回答
- 0 关注
- 78 浏览
添加回答
举报
0/150
提交
取消