Rectangle 27 0

php symfony: How to mock a response to an Guzzle Api request depending on the requested url?

private $mockLogger;
private $mockClient;
private $linkService;
public function prepareMocks($url, $json)
    $responseInterface = $this->getMockBuilder('\Guzzle\Http\Message\Response')

    $requestInterface = $this->getMock('\Guzzle\Http\Message\RequestInterface');

    $this->mockClient = $this->getMock('\Guzzle\Http\Client');

    $this->linkService = new DefaultPreviewImageLinkService($this->mockLogger, $this->mockClient);
public function testGetPreviewUrlBigImage()
    // Given:
    $url = '';
    $json = '{"60963198":{"0":{"url":"http:\/\/\/teaser\/320\/8\/60963198.jpeg",'
        . '"size":320,"type":""}}}';
    $this->prepareMocks($url, $json);

    $class_methods = get_class_methods($this->linkService);
    // When:
    $previewUrl = $this->linkService->getPreviewUrl(60963198, '', DefaultPreviewImageLinkService::IMAGE_BIG);
    // Then:

By preparing the mocks in a method I keep the code clean, because this has to be called for each test. I just feed the desired input valued into the prepareMock method.

By this the mock behaves like it should: it only gives back the desired value if the matching value is used by my tested class.

In the test methods it is called like follows:

With the help of francisco-spaeth I got this solved:

three private properties were added to the test class: