GlennM
GlennM

Reputation: 330

PHPUnit and mocking dependencies

I'm writing a test for the Service class. As you can see below, my Service class uses the Gateway class. I'd like to mock the output of getSomething() on the Gateway class in one of my tests.

I tried with stubs (createStub) & mocks (getMockBuilder), but PHPUnit does not produce the desired result.

My 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();
    }
}

(this project does not have a DI container yet)

Upvotes: 0

Views: 242

Answers (1)

Philip Weinke
Philip Weinke

Reputation: 1844

To mock your Gateway class, you have to inject it into the 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);
    }
}

Upvotes: 1

Related Questions