我正在為服務類編寫一個測試。正如您在下面看到的,我的服務類使用 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 關注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消