亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHPUnit 和模擬依賴項

PHPUnit 和模擬依賴項

PHP
慕哥9229398 2023-10-22 20:59:35
我正在為服務類編寫一個測試。正如您在下面看到的,我的服務類使用 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);

    }

}


查看完整回答
反對 回復 2023-10-22
  • 1 回答
  • 0 關注
  • 103 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號