When developing a complex system, you often need to be sure that a given dependency is checked by the encapsulating entity, in a precise manner.

For example, the wrapper of a HTTP Client needs to check that, at invocation of "send" method (to call a remote service) towards itself, the same method is invoked on the HTTP client, corresponding to a well defined URL.

For example, a first GoogleMap object encapsulates a Client type object, capable to connect to the remote system, allowing the conversion of a string containing an address, to the related location, expressed in terms of its latitude and longitude.

<?php

// src/GoogleMap.php
class GoogleMap
{
    private $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function decode($address)
    {
        if (!is_string($address)) {
            throw new InvalidArgumentException("Only strings please");
        }

        return $this->client->send($address);
    }
}

The purpose of our Test is to check that, when the address decoding method is invoked, a corresponding remote request is executed.

<?php

// tests/GoogleMapTest.php
class GoogleMapTest extends PHPUnit_Framework_TestCase
{
    public function testRequestIsSent()
    {
        $mock = $this->getMock('Client', ["send"]);

        $mock->expects($this->once())
            ->method("send")
            ->with($this->equalTo("Infinite Loop 1, Cupertino"))
        ;

        $sut = new GoogleMap($mock);

        $sut->decode("Infinite Loop 1, Cupertino");
    }
}

From the example, you can see the check to verify that the "send" method is invoked only once, via the check procedure "once()", and the check to verify that the invocation parameter is "Infinite Loop 1, Cupertino", via the "with" method of "send" method.

So the spies will allow to check that given behaviors are really present during the code execution loop.

Comments

comments powered by Disqus

cloudparty

Follow Us