PHPUnit 和模拟依赖项

我正在为服务类编写一个测试。正如您在下面看到的,我的服务类使用 Gateway 类。我想在我的一个测试中模拟网关类的输出。getSomething()


我尝试使用存根()和模拟(),但PHPUnit没有产生预期的结果。createStubgetMockBuilder


我的课程:


<?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 容器)


慕哥9229398
浏览 79回答 1
1回答

UYOU

要模拟您的类,您必须将其注入 .GatewayServiceclass Service{&nbsp; &nbsp; private $gateway;&nbsp; &nbsp; public function __construct(Gateway $gateway)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->gateway = $gateway;&nbsp; &nbsp; }&nbsp; &nbsp; public function getWorkspace()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->gateway->getSomething();&nbsp; &nbsp; }}class ServiceTest{&nbsp; &nbsp; public function test()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $gateway = $this->createMock(Gateway::class);&nbsp; &nbsp; &nbsp; &nbsp; $gateway->method('getSomething')->willReturn('something else');&nbsp; &nbsp; &nbsp; &nbsp; $service = new Service($gateway);&nbsp; &nbsp; &nbsp; &nbsp; $result = $service->getWorkspace();&nbsp; &nbsp; &nbsp; &nbsp; self::assertEquals('something else', $result);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP