PHPUnit 和模拟依赖项

PHPUnit and mocking dependencies

我正在为服务编写测试 class。如下所示,我的服务 class 使用网关 class。我想在我的一个测试中模拟网关 class 上 getSomething() 的输出。

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

我的 classes:

<?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 class,您必须将其注入 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);
    }
}